文章目录
- 抽象工厂
另外可参考:设计模式的UML图
抽象工厂
代码语言:javascript复制// 只定义了需要实现的内容
interface HtmlDoc {
void print();
}
// 只定义了需要实现的内容
interface WordDoc {
void print();
}
// 工厂是接口的
interface AbstractFactory {
HtmlDoc createHtml(String md);
WordDoc createWord(String md);
static AbstractFactory createFactory(String name) {
if ("fast".equalsIgnoreCase(name)) {
return new FastFactory();
}else if ("good".equalsIgnoreCase(name)) {
return new GoodFactory();
}else {
throw new IllegalArgumentException();
}
}
}
// 具体的接口实现类
class FastHtmlDoc implements HtmlDoc {
String md;
public FastHtmlDoc(String md) {this.md = md;}
@Override
public void print() {
System.out.println(md);
}
}
// 具体的接口实现类
class FastWordDoc implements WordDoc {
String md;
public FastWordDoc(String md) {this.md = md;}
@Override
public void print() {
System.out.println(md);
}
}
// Fast厂家提供的实际的工厂来生产这两种产品
class FastFactory implements AbstractFactory {
@Override
public HtmlDoc createHtml(String md) {
return new FastHtmlDoc(md);
}
@Override
public WordDoc createWord(String md) {
return new FastWordDoc(md);
}
}
// Good厂家提供的实际的工厂来生产这两种产品
class GoodFactory implements AbstractFactory {
@Override
public HtmlDoc createHtml(String md) {
return new FastHtmlDoc(md);
}
@Override
public WordDoc createWord(String md) {
return new FastWordDoc(md);
}
}
public class Main {
public static void main(String[] args) throws InterruptedException {
AbstractFactory factory1 = AbstractFactory.createFactory("fast");
HtmlDoc html1 = factory1.createHtml("fast html");
html1.print();
WordDoc word1 = factory1.createWord("fast word");
word1.print();
AbstractFactory factory2 = AbstractFactory.createFactory("good");
HtmlDoc html2 = factory2.createHtml("good html");
html2.print();
WordDoc word2 = factory2.createWord("good word");
word2.print();
}
}