zoukankan      html  css  js  c++  java
  • 易学设计模式看书笔记(3)


    二、工厂方法模式

    1.动物管理系统的样例

    首先,抽象的动物类和详细的动物实现类:
    
    public interface Animal{
    
      public void eat();
    
    }
    
    public class Tiger implements Animal
    {
    	public void eat(){
    		sysout.out.println("老虎会吃");
    	};
    	public void run(){
    		sysout.out.println("老虎会跑");
    	};
    }
    
    public class Dolphin implements Animal
    {
    	public void eat(){
    		sysout.out.println("海豚会吃");
    	};
    	public void swim(){
    		sysout.out.println("海豚会游泳");
    	};
    }
    
    然后设计一个仅仅负责定义创建方式的抽象工厂类:
    
    public interface Factory
    {
    	public Animal createAnimail();
    }
    
    再分别设计老虎、海豚的详细工厂实现类。都继承抽象工厂类:
    
    public class Trigerfactory implements Factory
    {
    	public Animal createAnimal(){
    		return new Triger();
    	}
    }
    
    public class Dolphinfactory implements Factory
    {
    	public Animal createAnimal(){
    		return new Dolphin();
    	}
    }
    
    client调用:
    
    public class Client
    {
    	public static void main(String[] args) 
    	{
    		Factory factory = new TrierFactory();
    		Animal animal = factory.createAnimal();
    		animal.eat();
    		factory = new DolphinFactory();
    		animal = fatory.createAnimal();
    		animal.eat();
    	}
    }
    

    2.工厂方法模式简单介绍

      定义:工厂方法模式中抽象工厂负责定义创建对象的接口,
      详细对象的创建工作由实现抽象工厂的详细工厂类来完毕。

    3.工厂方法模式的优缺点:

    长处:

        在工厂方法模式中。client不再负责对象的创建。
    而是把这个责任交给了详细的工厂类,client仅仅负责对象的调用,
    明白了各个类的职责。


        假设有新的产品加进来,仅仅须要添加一个详细的创建产品工厂类
    和详细的产品类,不会影响其它原有的代码,后期维护更加easy。
    增强了系统的可扩展性。

    缺点:
       
     须要额外的编写代码,添加了工作量。

  • 相关阅读:
    [中文] 以太坊(Ethereum )白皮书
    走近比特币:一个故事看懂“区块链”
    MAC下redis的安装和配置
    mysql查询优化
    mac上用VMWare虚拟机装Linux-Ubuntu
    rest-framework框架
    浅谈设计模式
    [BZOJ3786]星系探索(欧拉序+非旋treap)
    [SDOI2017]遗忘的集合(多项式ln+生成函数+莫比乌斯反演)
    [LuoguP4841]城市规划(多项式ln+生成函数)
  • 原文地址:https://www.cnblogs.com/clnchanpin/p/7327120.html
Copyright © 2011-2022 走看看