简单工厂模式比较简单,主要是将对象的创建和使用分离,隔离了客户端和具体实现类之间的关系。但是创建对象的时候还是存在很多条件判断,不利于后期维护:
interface Product {
}
class Product1 implements Product{
public String toString() {
return "this is product1" ;
}
}
class Product2 implements Product{
public String toString() {
return "this is product2" ;
}
}
class SimpleFactory {
public Product getInstance(String productName) {
if("Product1" .equals(productName)) {
return new Product1();
} else if ("Product2" .equals(productName)) {
return new Product2();
}
return null ;
}
}
public class Client {
public static void main(String[] args) {
SimpleFactory factory = new SimpleFactory();
Product product1 = factory.getInstance( "Product1");
System. out.println(product1);
Product product2 = factory.getInstance( "Product2");
System. out.println(product2);
}
}