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

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

相关推荐
geovindu16 小时前
rust: Simple Factory Pattern(续)
后端·设计模式·rust·简单工厂模式·创建型模式
喜欢coding的谢同学16 小时前
Go语言常用设计模式基础和实践案例介绍
开发语言·设计模式·golang
sarasuki1 天前
Agent 的记忆有几种?你的名字是?
人工智能·设计模式·agent
geovindu2 天前
rust: Flyweight Pattern
开发语言·后端·设计模式·rust·享元模式·结构型模式
沫璃染墨2 天前
《Linux工程实践篇(一):认识设计模式——从日志系统看策略模式》
linux·c++·安全·设计模式·策略模式
十六宿舍2 天前
【软件设计模式-第一课:基础知识了解】
设计模式·架构·面向对象·软件架构
geovindu2 天前
rust: Facade Pattern
开发语言·后端·设计模式·rust·外观模式
怕浪猫3 天前
面试官让我手写一个 Tool Use,我用了 3 种方案
设计模式·面试·程序员
geovindu3 天前
rust: Abstract Factory pattern
开发语言·后端·设计模式·rust·抽象工厂模式
Carl_奕然4 天前
【智能体】Loop 的四种设计模式之:Event-Driven Loop(2026 最新版)
人工智能·驱动开发·python·设计模式