首页 > 代码库 > 工厂模式和抽象工厂模式
工厂模式和抽象工厂模式
工厂模式: 定义一个用于创建对象的接口,让他的子类决定实例化哪个类.使类的实例化延迟到子类.
1.普通的工厂模式:
public class GoodProduct implements Product {
private String prodInfo = "Iam the good prod";
public String getProductInfo() {
// TODO Auto-generated method stub
return this.prodInfo;
}
public void setProdInfo(String prodInfo) {
// TODO Auto-generated method stub
this.prodInfo = prodInfo;
}
}
public class BadProduct implements Product {
public String getProductInfo() {
// TODO Auto-generated method stub
return "Iam the bad product";
}
public void setProdInfo(String prodInfo) {
// TODO Auto-generated method stub
}
}
public class ProdCreator implements Creator {
public <t extends Product> t getProd(Class<t> c) {
// TODO Auto-generated method stub
t ret = null;
try {
ret = (t) Class.forName(c.getName()).newInstance();
} catch (InstantiationException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IllegalAccessException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}finally{
return ret;
}
}
}
2。多个工厂的工厂模式:
public class BadProdCreator {
public Product getProd(){
return new BadProduct();
}
}
goodProdCreator 同理。
调用方法:
public static void main(String[] args) {
// TODO Auto-generated method stub
ProdCreator pc = new ProdCreator();
GoodProduct gp = pc.getProd(GoodProduct.class);
System.out.println(gp.getProductInfo());
BadProduct bp = pc.getProd(BadProduct.class);
System.out.println(bp.getProductInfo());
gp = SimpleCreator.getProd(GoodProduct.class);
bp = SimpleCreator.getProd(BadProduct.class);
System.out.println(gp.getProductInfo());
System.out.println(bp.getProductInfo());
BadProdCreator bpc = new BadProdCreator();
System.out.println(bpc.getProd().getProductInfo());
}
抽象工厂模式:为创建一组相关或者相互依赖的对象提供接口,无需指定具体的类。