工厂模式和抽象工厂模式的区别在于,工厂模式一个一个工厂对应生成一种产品,而抽象工厂模式在于可以一个工厂生产多种产品。
框架层
Item.java为元件父类
package abstractfactory.factory;
public abstract class Item {
protected String caption;
public Item(String caption) {
this.caption = caption;
}
public abstract String makeHTML();
}
Link.java为元件类
package abstractfactory.factory;
public abstract class Link extends Item {
protected String url;
public Link(String caption, String url) {
super(caption);
this.url = url;
}
}
Tray.java为元件类,同时作为item类的容器
package abstractfactory.factory;
import java.util.ArrayList;
public abstract class Tray extends Item {
protected ArrayList tray = new ArrayList();
public Tray(String caption) {
super(caption);
}
public void add(Item item) {
tray.add(item);
}
}
Page.java为产品类,同时作为Item的容器
package abstractfactory.factory;
import java.io.FileWriter;
import java.io.IOException;
import java.io.Writer;
import java.util.ArrayList;
public abstract class Page {
protected String title;
protected String author;
protected ArrayList content = new ArrayList();
public Page(String title, String author) {
this.title = title;
this.author = author;
}
public void add(Item item) {
content.add(item);
}
public void output() {
try {
String filename = title + ".html";
Writer writer = new FileWriter(filename);
writer.write(this.makeHTML());
writer.close();
System.out.println(filename + "writing is finished");
} catch (IOException e) {
e.printStackTrace();
}
}
public abstract String makeHTML();
}
Factory.java抽象工厂,可以创建link,tray,page
package abstractfactory.factory;
public abstract class Factory {
public static Factory getFactory(String classname) {
Factory factory = null;
try {
factory = (Factory)Class.forName(classname).newInstance();
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (InstantiationException e) {
e.printStackTrace();
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
return factory;
}
public abstract Link createLink(String captionm, String url);
public abstract Tray createTray(String caption);
public abstract Page createPage(String title, String author);
}
测试
Main.java类通过反射获得实例实现完全解耦
package abstractfactory.factory;
public class Main {
public static void main(String[] args) {
if (args.length != 1) {
System.exit(0);
}
Factory factory = Factory.getFactory(args[0]);
Link people = factory.createLink("People news ","https://www.peopel.com.cn");
Tray traynews = factory.createTray("News");
traynews.add(people);
Page page = factory.createPage("LinkPage", "news");
page.add(traynews);
page.output();
}
}