工厂模式(Factory)

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

做知识的过滤器和搬运工

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

 

简单工厂模式

        根据传入的参数创建对象。

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:      }
  在简单工厂上有所优化,去除了上帝类,增加专职工厂,不同工厂只管生产一个产品。不同工厂的区别在工厂创建时产生。
   

抽象工厂模式

       产品族概念产生。

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:      }
      抽象工厂模式,对工厂方法的衍生,对更一般事务的抽象。

 

posted @ 2013-11-28 16:48  但,我知道  阅读(643)  评论(0编辑  收藏  举报