简单工厂模式/Simple Factory
意图/适用场景:
如果系统中存在众多的产品类,而且这些产品类都可以抽象出统一的接口,简单工厂模式就可能会适用。
使用者不必自己去创建每一个产品类的实例,创建工作可以统统交给一个工厂类的实例来完成。使用者只需告诉工厂类所要创建的产品名字。
UML:
参与者:
- 抽象产品(Product):它是所有产品类的共有的接口,可以是一个接口或抽象类。
- 具体产品(ConcreteProduct):它代表每一个具体的产品类,实现Product接口。
- 工厂类(Factory):它是工厂模式的核心。它提供factory方法,接受应用程序的委托,按照应用程序的要求来创建具体产品,并以Product接口的形式返回给应用。
要点:
- 当有新产品加入时,只需要使它实现Product接口,并更新Factory类的factory方法。产品的创建仍然由factory方法这个统一的接口来管理。
- 因为Factory类的factory方法是所有产品的统一出口,所以它也常常被设计为静态方法。也正因为如此,了类无法继承静态方法,工厂类无法形成等级结构,这就限制了它的扩展。
- 所有产品都由factory方法来返回,这也是简单工厂模式的一个缺点。如果具体产品类比较多,而且继承关系很复杂的话,factory方法也可能会比较复杂。
- 如果Product接口需要增加新的接口的话,可能所有具体产品类都需要做相应的修改。
示例代码:
// Source code from file: ConcreteProduct1.java
package designPatterns. SimpleFactory;
public class ConcreteProduct1 implements Product {
public String toString ( ) {
return new String ( "ConcreteProduct1" );
}
}
// Source code from file: ConcreteProduct2.java
package designPatterns. SimpleFactory;
public class ConcreteProduct2 implements Product {
public String toString ( ) {
return new String ( "ConcreteProduct2" );
}
}
// Source code from file: Factory.java
package designPatterns. SimpleFactory;
public class Factory {
public static Product factory ( String s ) {
Product product = null;
if (s. equals ( "ConcreteProduct1" ) ) {
product = new ConcreteProduct1 ( );
} else if (s. equals ( "ConcreteProduct2" ) ) {
product = new ConcreteProduct2 ( );
}
return product;
}
}
// Source code from file: Product.java
package designPatterns. SimpleFactory;
public interface Product {
}
// Source code from file: User.java
package designPatterns. SimpleFactory;
public class User {
public static void main ( String [ ] args ) {
Product p = Factory. factory ( "ConcreteProduct1" );
System. out. println (p );
p = Factory. factory ( "ConcreteProduct2" );
System. out. println (p );
}
}
package designPatterns. SimpleFactory;
public class ConcreteProduct1 implements Product {
public String toString ( ) {
return new String ( "ConcreteProduct1" );
}
}
// Source code from file: ConcreteProduct2.java
package designPatterns. SimpleFactory;
public class ConcreteProduct2 implements Product {
public String toString ( ) {
return new String ( "ConcreteProduct2" );
}
}
// Source code from file: Factory.java
package designPatterns. SimpleFactory;
public class Factory {
public static Product factory ( String s ) {
Product product = null;
if (s. equals ( "ConcreteProduct1" ) ) {
product = new ConcreteProduct1 ( );
} else if (s. equals ( "ConcreteProduct2" ) ) {
product = new ConcreteProduct2 ( );
}
return product;
}
}
// Source code from file: Product.java
package designPatterns. SimpleFactory;
public interface Product {
}
// Source code from file: User.java
package designPatterns. SimpleFactory;
public class User {
public static void main ( String [ ] args ) {
Product p = Factory. factory ( "ConcreteProduct1" );
System. out. println (p );
p = Factory. factory ( "ConcreteProduct2" );
System. out. println (p );
}
}