作者:yanyige | 发布时间:2018-06-15 18:22

零、简单工厂概述

又称为静态工厂,定义一个具体的工厂类负责创建对象。

一、为什么需要工厂?

通过使用工厂模式,外界可以避免直接创建具体的对象,仅仅负责使用对象,而不必关心这些对象是如何封装及组成的,使软件结构更加清晰。

二、例子

1.外界直接创建对象

    Dog d = new Dog();
    Cat c = new Cat();

    d.eat();
    c.eat();

2.通过一个简单工厂来创建

    public class AnimalFactory {

        private AnimalFactory() {
    
        }
    
        public static Dog createDog() {
            return new Dog();
        }
    
        public static Cat createCat() {
            return new Cat();
        }
    }

3.方式2的改进

public class AnimalFactory {
    private AnimalFactory() {

    }

    public static Animal createAnimal(String type) {
        if(type.equals("cat")) {
            return new Cat();
        }
        if(type.equals("dog")) {
            return new Dog();
        }
        return null;
    }
}