您的位置:首页 > 其它

设计模式之工厂方法模式(简单工厂模式/工厂方法模式/抽象工厂模式)

2016-01-26 09:37 211 查看

工厂方法模式分三中:简单工厂模式、工厂方法模式、抽象工厂模式


    产品类:

  1. interface ICar{

  2.    void run();

  3. }

  4. public Class BMW  implements ICar{

  5.    public void run(){

  6.       System.println("宝马跑100码");

  7.    }

  8. }

  9. public Class LBJN implements ICar{

  10.    public void run(){

  11.       System.println("兰博基尼跑200码");

  12.    }

  13. }

  工厂类:

  1. public Class CarFactory{

  2.  

  3.    public ICar createCar(int case){

  4.        if(case == 100){

  5.           return new BMW();

  6.        }

  7.        if(case == 200){

  8.           return new LBJN();

  9.        }

  10.    }

  11. }

调用: 

  1. public Class Test{

  2.      //创建工厂实例对象

  3.      CarFactory factory = new CarFactory();

  4.      //获取产品并且执行方法

  5.      factory.createCar(200).run();

  6. }


 

产品类:

  1. interface ICar{

  2.    void run();

  3. }

  4. public Class BMW  implements ICar{

  5.    public void run(){

  6.       System.println("宝马跑100码");

  7.    }

  8. }

  9. public Class LBJN implementsICar{

  10.    public void run(){

  11.       System.println("兰博基尼跑200码");

  12.    }

  13. }

工厂类:

  1. //抽象工厂

  2. interface ICarFactory{

  3.   ICar createCar();

  4. }

  5. //创建宝马的工厂

  6. public Class BMWFactory implements ICarFactory{

  7.     ICar createCar(){

  8.       return new BMW();

  9.     }

  10. }

  11. //创建兰博基尼的工厂

  12. public Class LMJNFactory implements ICarFactory{

  13.     ICar createCar(){

  14.       return new LMJN();

  15.     }

  16. }

调用:

  1. public Class Test{

  2.      //创建抽象工厂实例对象指向宝马factory

  3.      ICarFactory factory = new BMWFactory();

  4.      //获取产品并且执行方法

  5.      factory.createCar().run();

  6. }


产品类:

  1. //食品类产品族

  2. interface IFood{

  3.    void eat();

  4. }

  5. public Class SummerFood implements IFood{

  6.   void eat(){

  7.     }

  8. }

  9. public Class WinnerFood implements IFood{

  10.   void eat(){

  11.     }

  12. }

  13. //衣服类产品族

  14. interface ICloths{

  15.    void dress();

  16. }

  17. public Class SummerCloths implements ICloths{

  18.     void dress(){}

  19. }

  20. public Class WinnerCloths implements ICloths{

  21.     void dress(){}

  22. }

工厂类:

  1. interface IFactory{

  2.   IFood createFood();

  3.   ICloths createCloths();

  4. }

  5. Public Class SummerFactory(){

  6.    IFood createFood(){

  7.      return new SummerFood();

  8.    }

  9.    ICloths createCloths(){

  10.      return new SummerCloths();

  11.    }

  12. }

  13. Public Class WinnerFactory(){

  14.    IFood createFood(){

  15.      return new WinnerFood();

  16.    }

  17.   ICloths createCloths(){

  18.      return new WinnerCloths();

  19.    }

  20. }


内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐