设计模式(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

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

相关推荐
Cosolar9 小时前
DeepSeek Harness 理解 Harness 的设计哲学 - 可组合的插件运行时
人工智能·设计模式·架构
Nebula_g10 小时前
JavaSE基础语法:特殊类(特殊情景下的设计模式)
java·开发语言·设计模式
George_Ye1 天前
同一本书,一人一份:我如何设计 AI 个性化扫书报告
设计模式
莫得感情 o1 天前
设计模式 22 · 三个冷门模式:中介者、访问者、解释器
java·设计模式
AI人工智能+电脑小能手2 天前
大白话说Java设计模式-08-建造者模式(业务实战篇)
java·设计模式·建造者模式·架构设计·对象构建
AustinXu2 天前
从 Claude Code 到 Claude Tag,Harness Engineering 走到了组织这一层
设计模式·团队管理
剧中有戏2 天前
单例模式从入门到精通:一个数据库连接池的完整剖析
设计模式
胡萝卜术2 天前
编译期与运行期的双重防线:从 TypeScript 类型之争到 LLM 输出的自动化择优
前端·设计模式·面试
货拉拉技术2 天前
重塑 Agent 度量衡:基于 LLM-as-a-Judge 的离线评估体系与实践
算法·设计模式
KhalilRuan2 天前
设计模式小记
设计模式