// 产品接口 ? ? ? ??
public interface Product { ??
? ? public void getName(); ??
} ??
??
// 具体产品A ??
public class ProductA implements Product { ??
? ? public void getName() { ??
? ? ? ? System.out.println(" ?I am ProductA ?"); ??
? ? } ??
} ??
??
// 具体产品B ??
public class ProductB implements Product { ??
? ? public void getName() { ??
? ? ? ? System.out.println(" ?I am ProductB ?"); ??
? ? } ??
} ??
??
// 工厂类 ??
public class ProductCreator { ??
? ? public Product createProduct(String type) { ??
? ? ? ? if (" A ".equals(type)) { ??
? ? ? ? ? ? return new ProductA(); ??
? ? ? ? } ??
? ? ? ? if (" B ".equals(type)) { ??
? ? ? ? ? ? return new ProductB(); ??
? ? ? ? } else ?
? ? ? ? ? ? return null; ??
? ? } ??
? ? public static void main(String[] args) { ??
? ? ? ? ProductCreator creator = new ProductCreator(); ??
? ? ? ? creator.createProduct(" A ").getName(); ??
? ? ? ? creator.createProduct(" B ").getName(); ??
? ? } ??
} ?
?
--------------------------------另一种设计模式-----------------------------------
// 产品接口 ? 具体产品A ??具体产品B ? 不变,仅仅改变工厂实现,就是一种新模式,小伙伴知道这是一种什么模式吗?
//工厂类 ??
public class ProductCreator { ??
?
public void createProduct(Product p) {?
p.getName();
System.out.println("------ProductCreator------p.getName");
}?
}
?
public static void main(String[] args) { ??
? ? ? ? ProductCreator creator = new ProductCreator(); ??
? ? ? ? creator.createProduct(new ProductA());
? ? ? ? ?creator.createProduct(new ProductB());
? ? } ??
?
原文:http://gaojingsong.iteye.com/blog/2281168