Java设计模式之抽象工厂(02)
对工厂方法进行抽象。当增加新的产品时,不用改动工厂类。而是集成已有的工厂接口或者抽象工厂,创建新的工厂。这就是对扩展开发,对修改封闭。
1 package Pak; 2 3 public abstract class Automobile { 4 public abstract void Run(); 5 }
package Pak; public class Bus extends Automobile { @Override public void Run() { System.out.println("Bus Run"); } }
package Pak; public class Jeep extends Automobile { @Override public void Run() { System.out.println("Jeep Run."); } }
1 package Pak; 2 3 public interface IProduce { 4 public Automobile Produce(); 5 }
package Pak; public class BusFactory implements IProduce { @Override public Automobile Produce() { // TODO Auto-generated method stub return new Bus(); } }
package Pak; public class JeepFactory implements IProduce { @Override public Automobile Produce() { return new Jeep(); } }
1 package Pak; 2 3 public class Main { 4 5 public static void main(String[] args) throws Exception { 6 IProduce busFactory=new BusFactory(); 7 busFactory.Produce().Run(); 8 9 IProduce jeepFactory=new JeepFactory(); 10 jeepFactory.Produce().Run(); 11 } 12 }
posted on 2014-07-08 21:48 Henry_Wang 阅读(260) 评论(0) 编辑 收藏 举报