【设计模式】简单工厂模式(Simple Factory Pattern)

工厂模式(Factory Pattern)

用于创建不同类型的奖品对象。您可以创建一个奖品工厂,根据配置的类型来实例化相应的奖品对象。

java 复制代码
public interface Prize {
    void award();
}

public class MoneyPrize implements Prize {
    @Override
    public void award() {
        // 实现发放金额奖品的逻辑
    }
}

public class ItemPrize implements Prize {
    @Override
    public void award() {
        // 实现发放物品奖品的逻辑
    }
}

public class PrizeFactory {
    public Prize createPrize(String type) {
        if ("money".equalsIgnoreCase(type)) {
            return new MoneyPrize();
        } else if ("item".equalsIgnoreCase(type)) {
            return new ItemPrize();
        }
        // 可以添加更多类型的奖品
        return null;
    }
}

这段代码属于简单工厂模式(Simple Factory Pattern)。简单工厂模式是一种类创建型设计模式,它提供一个静态方法来创建对象,这个方法根据传入的参数来决定创建哪个类的实例。在这个例子中,PrizeFactory是工厂类,它根据字符串type来决定创建MoneyPrize或ItemPrize的实例。MoneyPrize和ItemPrize都实现了Prize接口,因此它们都是产品类。通过工厂方法createPrize(),客户端可以得到一个符合Prize接口的对象,而无需知道具体的实现类。 这段代码属于简单工厂模式。

相关推荐
geovindu8 小时前
python: Template Method Pattern
开发语言·python·设计模式·模板方法模式
HY小海13 小时前
【Unity游戏创作】常见的设计模式
unity·设计模式·c#·游戏程序
Yongqiang Cheng13 小时前
设计模式:C++ 模板方法模式 (Template Method in C++)
设计模式·template method·c++ 模板方法模式
我爱cope14 小时前
【从0开始学设计模式-3| 工厂模式】
设计模式
资深web全栈开发1 天前
设计模式之空对象模式 (Null Object Pattern)
设计模式
我爱cope1 天前
【从0开始学设计模式-2| 面向对象设计原则】
设计模式
资深web全栈开发1 天前
设计模式之访问者模式 (Visitor Pattern)
设计模式·访问者模式
sg_knight2 天前
对象池模式(Object Pool)
python·设计模式·object pool·对象池模式
Yongqiang Cheng2 天前
设计模式:C++ 单例模式 (Singleton in C++)
设计模式·c++ 单例模式
得一录2 天前
AI Agent的主流设计模式之反射模式
人工智能·设计模式