工厂方法模式引入了抽象的工厂类,而将具体产品的创建过程封装在抽象工厂类的子类,也就是具体工厂类中。客户端代码针对抽象层进行编程,增加新的具体产品类时只需要增加一个相应的具体工厂类即可,使得系统具有更好的灵活性和可扩展性。
代码实现:
(1)抽象产品类
public Interface TV{
public void play();
}
(2)具体产品类:
public class HaierTV implements TV{
public void play(){
System.out.println("海尔电视机播放中");
}
}
(3)具体产品类:
public class HisenseTV implements TV{
public void play(){
System.out.println("海信电视机播放中");
}
}
(4)抽象工厂类
public interface TVFactory{
public TV produceTV();
}
(5)具体工厂类
public class HaierTVFactory implements TVFactory{
public TV produceTV(){
System.out.println("海尔电视机工厂生产海尔电视机");
return new HaierTV();
}
}
(6)具体工厂类
public class HisenseTVFactory implements TVFactory{
public TV produceTV(){
System.out.println("海信电视机工厂生产海信电视机");
return new HisenseTV ();
}
}
(7)客户端代码
public class client{
public static void main(String [] args){
TV tv;
TVFactory factory;
factory=new HaierTVFactory ();
tv=factory.produceTV();
TV.play();
}
}