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

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

相关推荐
Zane19945 天前
一个 new 就能创建对象,为什么还要拆出单例、工厂、建造者、原型四种模式?
设计模式
怕浪猫5 天前
一行命令复刻爆款视频,我把 Hypit 从安装跑到了出片
人工智能·设计模式·程序员
Zane19946 天前
函数式编程里的函数,其实不是你天天写的那个函数——三大编程范式的边界在哪
设计模式
Zane19947 天前
策略模式现在该不该上?一次讲清楚过度设计和设计不足怎么找平衡
设计模式
她说..7 天前
常见设计模式-模板方法模式
java·spring·设计模式·springboot
xiaofeiyang1507 天前
第六章 · 桥接 — 三支毛笔,画出九种颜色
设计模式
Shadow(⊙o⊙)8 天前
OTOL设计模式 One Thread One Loop
服务器·网络·设计模式
sarasuki8 天前
如何让LLM 能在半夜偷偷打开网易云呢?
人工智能·设计模式·agent
小王师傅668 天前
【设计模式】装饰模式(四):框架源码实战——从 Java I/O 到 Spring 到 MyBatis
java·设计模式
执明wa9 天前
Android RecyclerView 多类型, 多种 Item
android·xml·开发语言·设计模式·android studio