设计模式(2)工厂模式

让一个工厂类去生产出对象 (new )来。

我们想要一个 形状,我们用工厂去生产出,圆形,方形。

java 复制代码
package com.example.factory2;

public interface Shape {
    void draw();
}
java 复制代码
public class Square implements Shape {
    @Override
    public void draw() {
        Log.d("LIU", "this is Square");
    }
}
java 复制代码
public class Circle implements Shape {
    @Override
    public void draw() {
        Log.d("LIU","this is circle");
    }
}

factory class:

java 复制代码
public class ShapeFactory {
    public Shape getShape (int type) {
        if (type == 1) {
            return new Circle();
        } else if (type ==2) {
            return  new Square();
        } else {
            return null;
        }

    }
}

example and output:

java 复制代码
        ShapeFactory shapeFactory = new ShapeFactory();
        Shape shape = shapeFactory.getShape(1);
        shape.draw();
        Shape shape2 = shapeFactory.getShape(2);
        shape2.draw();



2024-10-02 22:23:47.705 14673-14673/com.example.factory2 D/LIU: this is circle
2024-10-02 22:23:47.706 14673-14673/com.example.factory2 D/LIU: this is Square

参考: 工厂模式 | 菜鸟教程

相关推荐
百度智能云技术站1 小时前
百度百舸万卡集群的训练稳定性系统设计和实践
设计模式
Seven972 小时前
【设计模式】享元模式教你如何分离内部与外部状态
java·后端·设计模式
Seven973 小时前
【设计模式】利用组合模式带你走进树形结构的世界
java·后端·设计模式
Seven973 小时前
【设计模式】掌握算法骨架:利用模板方法模式实现代码复用
java·后端·设计模式
Seven973 小时前
【设计模式】从智能音箱到软件设计:探索外观模式的实际应用案例
java·后端·设计模式
Seven973 小时前
【设计模式】如何通过桥接模式解决系统扩展难题?
java·后端·设计模式
Seven973 小时前
【设计模式】告别继承噩梦:用装饰者模式简化代码结构
java·后端·设计模式
Seven974 小时前
【设计模式】如何使用适配器模式让不兼容的类协同工作?
java·后端·设计模式
香菇滑稽之谈4 小时前
装饰器模式的C++实现示例
c++·算法·设计模式·装饰器模式
牵牛老人4 小时前
C++设计模式-简单工厂模式:从原理、应用、实践指南与常见问题和解决方案深度解析
c++·设计模式·简单工厂模式