设计模式(2)工厂模式

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

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

package com.example.factory2;

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

factory class:

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:

        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

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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值