JAVA设计模式(系列) 工厂模式

工厂模式(Factory Pattern)是 Java 中最常用的设计模式之一。这种类型的设计模式属于创建型模式,它提供了一种创建对象的最佳方式。

在工厂模式中,我们在创建对象时不会对客户端暴露创建逻辑,并且是通过使用一个共同的接口来指向新创建的对象。

符合java的单一原则,开闭原则

/**
 * 设计模式 – 工厂模式
 */
public class FactoryDemo {
    //使用 getShape 方法获取形状类型的对象
    public animal getAnimal(String type) {
        if (type == null) {
            return null;
        }
        if (type.equalsIgnoreCase("dog")) {
            return new Dog();
        } else if (type.equalsIgnoreCase("cat")) {
            return new Cat();
        }
        return null;
    }

    public static void main(String[] args) {
        FactoryDemo factoryDemo = new FactoryDemo();

        //获取animal对象
        animal animal = factoryDemo.getAnimal("dog");
        animal.doSomeThing();

        animal animal1 = factoryDemo.getAnimal("cat");
        animal1.doSomeThing();
    }

}
interface animal{
    void doSomeThing();
}
class Dog implements animal{

    @Override
    public void doSomeThing() {
        System.out.println("wang  wang.....");
    }
}
class Cat implements animal{

    @Override
    public void doSomeThing() {
        System.out.println("miao miao .....");
    }
}
发布了55 篇原创文章 · 获赞 3 · 访问量 5224

猜你喜欢

转载自blog.csdn.net/qq_38130094/article/details/104071837
今日推荐