• 工厂方法模式


    工厂方法概述

    工厂方法模式中抽象工厂类负责定义创建对象的接口,具体对象的创建工作由继承抽象工厂的具体类实现。

    优点

    客户端不需要在负责对象的创建,从而明确了各个类的职责,如果有新的对象增加,只需要增加一个具体的类和具体的工厂类即可,不影响已有的代码,后期维护容易,增强了系统的扩展性

    缺点

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

    public class IntegerDemo {
    	public static void main(String[] args) {
    		Factory factory = new DogFactory();
    		Animal animal = factory.createAnimal();
    		animal.eat();
    
    		factory = new CatFactory();
    		animal = factory.createAnimal();
    		animal.eat();
    	}
    }
    
    abstract class Animal {// 抽象类
    	public abstract void eat();
    }
    
    class Dog extends Animal {// 狗
    	public void eat() {
    		System.out.println("a dog is eatting.");
    	}
    }
    
    class Cat extends Animal {// 猫
    	public void eat() {
    		System.out.println("a cat is eatting.");
    	}
    }
    
    interface Factory {// 接口
    	public abstract Animal createAnimal();
    }
    
    class DogFactory implements Factory {// 实现接口
    	public Animal createAnimal() {
    		return new Dog();
    	}
    }
    
    class CatFactory implements Factory {// 实现接口
    	public Animal createAnimal() {
    		return new Cat();
    	}
    }
    
  • 相关阅读:
    修改服务器时间及时区
    风情万种awk
    追忆似水流年sed
    lvm笔记
    正则不怎么会用
    在CentOS7.5的虚拟环境下新建你的django项目
    Django学习过程中的排错总结
    我一直记不住的vim用法
    关于自建yum源拾遗
    Djangp2.x版本报错找不到模版目录下的文件
  • 原文地址:https://www.cnblogs.com/denggelin/p/6348109.html
Copyright © 2020-2023  润新知