接下來我將寫點設計模式的,大部分是從各位名家看到的,固然會間雜本身的一些理解。html
作知識的過濾器和搬運工設計模式
工廠模式有三種,分別是簡單工廠模式、工廠方法和抽象工廠模式,屬於建立型模式。固然沒有最好,只有最合適。優化
根據傳入的參數建立對象。spa
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: }
工廠類至關於上帝類,提供靜態方法來建立全部產品(這裏是中國人、美國人),你叫他造中國人就造中國人,你的話就是傳入參數,這能夠是字符串,也能夠是枚舉。
專注工廠出現。設計
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
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: }