zoukankan      html  css  js  c++  java
  • 工厂模式

    工厂模式方法模式:

    工厂方法模式中抽象工厂类负责定义创建对象的接口,

    具体对象的创建工作由继承抽象工厂的具体类实现。

    优点:

    客户端不需要在负责对象的创建,从而明确了各个类的职责,如果有新的对象增加,

    只需要增加一个具体的类和具体的工厂类即可,不影响已有的代码,后期维护容易,

    增强了系统的扩展性。

    缺点:

    需要额外的编写代码,增加了工作量

    如下:一个造动物的工厂

    1.动物接口
    package shejimoshi.Factory;
    //动物接口
    public interface Animal {
     public abstract void eat();
    }
    2.动物工厂接口
    package shejimoshi.Factory;
    //动物工厂接口
    public interface AnimalFactory {
       public abstract Animal creatAniaml();
    }
    

     3.具体动物

    package shejimoshi.Factory.impl;
    
    import shejimoshi.Factory.Animal;
    //具体动物猫
    public class Cat implements Animal {
    
    
    	public void eat() {
    		System.out.println("猫吃鱼");
    	}
    
    }
    

      

    package shejimoshi.Factory.impl;
    
    import shejimoshi.Factory.Animal;
    //具体动物狗
    public class Dog implements Animal {
    
    	public void eat() {
    		System.out.print("狗吃肉");
    
    	}
    
    }
    

      4.具体动物工厂

    package shejimoshi.Factory.impl;
    
    import shejimoshi.Factory.Animal;
    import shejimoshi.Factory.AnimalFactory;
    //具体造猫厂
    public class CatFactory implements AnimalFactory {
    
    	
    	public Animal creatAniaml() {
    		
    		return new Cat();
    	}
    
    }
    

      

    package shejimoshi.Factory.impl;
    
    import shejimoshi.Factory.Animal;
    import shejimoshi.Factory.AnimalFactory;
    //具体造狗厂
    public class DogFactory implements AnimalFactory {
    
    	
    	public Animal creatAniaml() {
    		
    		return new Dog();
    	}
    
    }
    

      5.测试test

    package shejimoshi.Factory;
    
    import shejimoshi.Factory.impl.CatFactory;
    import shejimoshi.Factory.impl.DogFactory;
    //测试类
    public class test {
    public static void main(String[] args) {
    	AnimalFactory dog=new DogFactory();
    	dog.creatAniaml().eat();
    	System.out.println();
    	AnimalFactory cat=new CatFactory();
    	cat.creatAniaml().eat();
    }
    }
    

      如果需要造新动物只需要在3,4步添加具体动物和对应的具体动物工厂即可。

  • 相关阅读:
    选项卡
    使用script创建标签添加属性值和添加样式
    判断表单不能为空(表格形式的)
    数组
    关于meta元信息元素
    js判断数据类型
    Ising模型的Metropolis模拟中的组态阻塞和振荡
    python 画能级图
    python 调用 shell 命令,制作用户界面
    打包 python 程序,变成一个可执行文件
  • 原文地址:https://www.cnblogs.com/ysg520/p/9561113.html
Copyright © 2011-2022 走看看