设计模式-工厂模式

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

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();
    }
}

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

更易于扩展;

缺点:代码复杂度提高

相关推荐
帅中的小灰灰3 小时前
C++编程建造器设计模式
java·c++·设计模式
ZHE|张恒3 小时前
设计模式(十)外观模式 — 提供统一入口,简化复杂系统的使用
设计模式·外观模式
howcode6 小时前
女友去玩,竟带回一道 “虐哭程序员” 的难题
后端·设计模式·程序员
apigfly1 天前
深入Android系统(十三)Android的窗口系统
android·设计模式·源码
y***54881 天前
Java设计模式之观察者模式
观察者模式·设计模式
明洞日记1 天前
【设计模式手册010】组合模式 - 树形结构的优雅处理
java·设计模式·组合模式
帅中的小灰灰1 天前
C++编程策略设计模式
开发语言·c++·设计模式
鲸沉梦落1 天前
23种常见设计模式
设计模式
Malone-AI2 天前
设计模式之单例模式
单例模式·设计模式
Moe4882 天前
Spring Boot 自动配置核心:AutoConfigurationImportSelector 深度解析
java·后端·设计模式