设计模式之简单工厂模式

首先我们来看看代码实现

 1.创建接口

// 动物接口
interface Animal {
    void speak(); // 每种动物都会叫
}

// 猫类
class Cat implements Animal {
    public void speak() {
        System.out.println("喵喵喵!");
    }
}

// 狗类
class Dog implements Animal {
    public void speak() {
        System.out.println("汪汪汪!");
    }
}

2.创建工厂类(动物工厂)

class AnimalFactory {
    // 静态方法,根据传入的类型返回对应的动物
    public static Animal createAnimal(String type) {
        if ("cat".equals(type)) {
            return new Cat(); // 你要猫,就给你一只猫
        } else if ("dog".equals(type)) {
            return new Dog(); // 你要狗,就给你一只狗
        } else {
            return null; // 如果要的动物不在店里,返回空
        }
    }
}

3.测试

public class Main {
    public static void main(String[] args) {
        // 你想要一只猫
        Animal cat = AnimalFactory.createAnimal("cat");
        cat.speak(); // 输出:喵喵喵!

        // 你想要一只狗
        Animal dog = AnimalFactory.createAnimal("dog");
        dog.speak(); // 输出:汪汪汪!
    }
}

这个代码怎么理解?

Animal接口:就像商店的动物标准,规定了动物都会“叫”。

Cat和Dog类:具体的动物,猫会“喵喵喵”,狗会“汪汪汪”。

AnimalFactory类:动物商店,你告诉它要“cat”还是“dog”,它就帮你把动物带出来。

Main类:你(顾客),去商店要动物,然后听它们叫。

简单工厂模式的好处

简单:你不用自己new Cat()或new Dog(),直接找工厂就行。

集中管理:如果以后商店想加只“鸟”,只需要在AnimalFactory里加一个if分支就行,其他地方不用改。

方便使用:你只管要动物,不用管怎么“造”动物。

你可能感兴趣的:(设计模式,设计模式,简单工厂模式,java)