一,结构图
工厂类角色Creator (LightSimpleFactory):
工厂类在客户端的直接控制下(Create方法)创建产品对象。
抽象产品角色Product (Light):
定义简单工厂创建的对象的父类或它们共同拥有的接口。可以是一个类、抽象类或接口。
具体产品角色ConcreteProduct (BulbLight, TubeLight):
定义工厂具体加工出的对象。
二,示例代码
public interface Light { public void turnOn(); public void turnOff(); } public class BulbLight implements Light { public void turnOn() { System.out.printLn("Bulb Light is Turned on"); } public void turnOff() { System.out.printLn("Bulb Light is Turned off"); } } public class TubeLight implements Light { public void turnOn() { System.out.printLn("Tube Light is Turned on"); } public void turnOff() { System.out.printLn("Tube Light is Turned off"); } } public class LightSimpleFactory { public Light Create(string lightType) { if(lightType == "Bulb") return new BulbLight(); else if(lightType == "Tube") return new TubeLight(); else return null; } }
三,演化
在有些情况下Simple Factory可以由抽象产品角色扮演,一个抽象产品类同时是子类的工厂。
public abstract class Light { public abstract void TurnOn(); public abstract void TurnOff(); public static Light create(string lightType) { if(lightType == "Bulb") return new BulbLight(); else if(lightType == "Tube") return new TubeLight(); else return null; } } public class BulbLight extends Light { public void turnOn() { System.out.printLn("Bulb Light is Turned on"); } public void turnOff() { System.out.printLn("Bulb Light is Turned off"); } } public class TubeLight extends Light { public void turnOn() { System.out.printLn("Tube Light is Turned on"); } public void TurnOff() { System.out.printLn("Tube Light is Turned off"); } }