工廠模式(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:      }
      抽象工廠模式,對工廠方法的衍生,對更通常事務的抽象。
相關文章
相關標籤/搜索