设计模式-工厂模式

工厂模式:该模式是将简单工厂模式中的工厂作为一个基类(接口),当需要创建的产品(具体子类实例)增加时,不修改原工厂的创建方法,而是增加一个具体工厂子类,由该子类去创建新增的产品,将产品子类的实例化延迟到工厂子类中。

cs 复制代码
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public interface Phone
{
    void Name();
}

public class IPhone : Phone
{
    public void Name()
    {
        Debug.Log("苹果手机");
    }
}

public class AZPhone : Phone
{
    public void Name()
    {
        Debug.Log("安卓手机");
    }
}

这是工厂的实现

cs 复制代码
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public interface IFactory
{
    Phone Creat();
}

public class IPhoneFactory : IFactory
{
    public Phone Creat()
    {
        return new IPhone();
    }
}

public class AZPhoneFactory : IFactory
{
    public Phone Creat()
    {
        return new AZPhone();
    }
}

优点:降低了耦合性,只需要知道要什么产品,不用管创建过程;

更易于扩展;

缺点:代码复杂度提高

相关推荐
刀法如飞15 小时前
Palantir Ontology 存储结构与读写机制原理深入剖析
大数据·设计模式·系统架构
KobeSacre17 小时前
设计模式——七大设计原则
设计模式
倒流时光三十年19 小时前
设计模式 之 责任链模式
设计模式·责任链模式
阿文的代码库21 小时前
桥接设计模式的案例实现
设计模式
乐观的山里娃21 小时前
【设计模式 14】责任链:谁来拍板
设计模式
乐观的山里娃1 天前
【设计模式 08】装饰器:加钱加服务
设计模式
魔法阵维护师2 天前
从零开发游戏需要学习的c#模块,第十章(设计模式入门)
学习·游戏·设计模式·c#
用户356302904872 天前
【设计模式】组合模式——树形结构的统一处理
设计模式
乐观的山里娃2 天前
【设计模式 12】原型:复制成功
设计模式
傻啦嘿哟2 天前
办公Agent与人工审核的“握手协议”:关键操作二次确认的设计模式
设计模式