工厂模式(Factory)

接下来我将写点设计模式的,大部分是从各位名家看到的,固然会间杂本身的一些理解。html

作知识的过滤器和搬运工设计模式

工厂模式有三种,分别是简单工厂模式工厂方法抽象工厂模式,属于建立型模式。固然没有最好,只有最合适。优化

 

简单工厂模式

        根据传入的参数建立对象。spa

UML:

image

       

代码:

   1:  public static void main(String[] args) {
   2:          Person chineser=PersonFactory.getPerson("Chinese");
   3:          Person american=PersonFactory.getPerson("American");
   4:          System.out.println(chineser.sayHello("张三"));
   5:          System.out.println(american.sayHello("张三"));
   6:          /*
   7:           * 你好,张三
   8:          *  hello,张三
   9:           */
  10:      }
      工厂类至关于上帝类,提供静态方法来建立全部产品(这里是中国人、美国人),你叫他造中国人就造中国人,你的话就是传入参数,这能够是字符串,也能够是枚举。
 

工厂方法

      专注工厂出现。设计

UML:

 

 

image

 

代码:

   1:   public static void main(String[] args) {
   2:          IAnimalFactory catFactory=new CatFactory();
   3:          IAnimal cat=catFactory.createAnimal();
   4:          cat.eat();
   5:          
   6:          IAnimalFactory dogFactory=new DogFactory();
   7:          IAnimal dog=dogFactory.createAnimal();
   8:          dog.eat();
   9:          
  10:          /*
  11:           * cat eating!
  12:           * dog eating!
  13:           */
  14:      }
  在简单工厂上有所优化,去除了上帝类,增长专职工厂,不一样工厂只管生产一个产品。不一样工厂的区别在工厂建立时产生。
   

抽象工厂模式

       产品族概念产生。code

UML:

image

 

代码:

   1:  public static void main(String[] args) {
   2:          IAnimalFactory blackAnimalFactory=new BlackAnimalFactory();
   3:          ICat blackCat=blackAnimalFactory.createCat();
   4:          blackCat.eat();
   5:          IDog blackDog=blackAnimalFactory.createDog();
   6:          blackDog.bark();
   7:          
   8:          IAnimalFactory whiteAnimalFactory=new WhiteAnimalFactory();
   9:          ICat whiteCat=whiteAnimalFactory.createCat();
  10:          whiteCat.eat();
  11:          IDog whiteDog=whiteAnimalFactory.createDog();
  12:          whiteDog.bark();
  13:  //        The black cat is eating!
  14:  //        The black dog is barking!
  15:  //        The White cat is eating!
  16:  //        The White dog is barking!
  17:      }
      抽象工厂模式,对工厂方法的衍生,对更通常事务的抽象。
相关文章
相关标签/搜索