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

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

相关推荐
xiaodaidai丶20 分钟前
设计模式之策略模式
设计模式·策略模式
_院长大人_1 小时前
设计模式-工厂模式
java·开发语言·设计模式
王道长服务器 | 亚马逊云16 小时前
AWS + 苹果CMS:影视站建站的高效组合方案
服务器·数据库·搜索引擎·设计模式·云计算·aws
在未来等你17 小时前
AI Agent设计模式 Day 1:ReAct模式:推理与行动的完美结合
设计模式·llm·react·ai agent·plan-and-execute
乐悠小码1 天前
Java设计模式精讲---03建造者模式
java·设计模式·建造者模式
_院长大人_1 天前
设计模式-代理模式
设计模式·代理模式
guangzan1 天前
TypeScript 中的单例模式
设计模式
乐悠小码2 天前
Java设计模式精讲---02抽象工厂模式
java·设计模式·抽象工厂模式
乙己4073 天前
设计模式——原型模式(prototype)
设计模式·原型模式
⑩-3 天前
浅学Java-设计模式
java·开发语言·设计模式