Unity中常见的设计模式

前言

        设计模式是一系列被广泛使用且具有相似解决方案的问题或问题实例的解决方法。它们是软件设计领域中的通用解决方案,可以帮助开发人员轻松地解决常见的软件设计问题。对于Unity开发者来说,熟悉并掌握常用的设计模式可以帮助我们更好地组织和管理代码,提高代码可读性、可维护性和可扩展性。

        篇博客将会介绍Unity中的23种常用设计模式,每种设计模式都会给出详细的示例代码。希望这篇博客对Unity的开发者有所帮助。

1. 单例模式(Singleton)

        单例模式用于保证一个类只有一个实例,并且该实例可以全局访问。在Unity中,这种模式常用于管理游戏系统或资源,例如游戏设置,场景管理,音效管理等。

以下是Singleton模式的示例代码:

public class Singleton
{
    private static Singleton _instance;

    public static Singleton Instance
    {
        get
        {
            if (_instance == null)
            {
                _instance = new Singleton();
            }
            return _instance;
        }
    }

    private Singleton()
    {
        // 构造函数
    }
}

2. 工厂模式(Factory)

        工厂模式用于创建对象,它将对象的创建过程封装在一个工厂类中,使得客户端程序无需直接调用对象的构造函数来创建对象,而只需要调用工厂类的方法即可。

以下是Factory模式的示例代码:

public interface IProduct 
{
    void Use();
}

public class ConcreteProduct : IProduct 
{
    public void Use() 
    {
        Debug.Log("ConcreteProduct");
    }
}

public abstract class Factory 
{
    public abstract IProduct Create();
}

public class ConcreteFactory : Factory 
{
    public override IProduct Create() 
    {
        return new ConcreteProduct();
    }
}

3. 抽象工厂模式(Abstract Factory)

        抽象工厂模式是工厂模式的拓展,它用于创建一组相关或依赖对象的族群,而不需要指定特定类。通常我们会将每个族群的对象都抽象成类,并由工厂来负责具体对象的创建。

以下是Abstract Factory模式的示例代码:

public interface IButton 
{
    void Paint();
}

public interface ICheckbox 
{
    void Paint();
}

public abstract class GUIFactory 
{
    public abstract IButton CreateButton();
    public abstract ICheckbox CreateCheckbox();
}

public class WinFactory : GUIFactory 
{
    public override IButton CreateButton() 
    {
        return new WinButton();
    }

    public override ICheckbox CreateCheckbox()
    {
        return new WinCheckbox();
    }
}

public class MacFactory : GUIFactory 
{
    public override IButton CreateButton()
    {
        return new MacButton();
    }

    public override ICheckbox CreateCheckbox()
    {
        return new MacCheckbox();
    }
}

public class WinButton : IButton 
{
    public void Paint() 
    {
        Debug.Log("Windows Button");
    }
}

public class WinCheckbox : ICheckbox 
{
    public void Paint() 
    {
        Debug.Log("Windows Checkbox");
    }
}

public class MacButton : IButton 
{
    public void Paint() 
    {
        Debug.Log("Mac Button");
    }
}

public class MacCheckbox : ICheckbox 
{
    public void Paint() 
    {
        Debug.Log("Mac Checkbox");
    }
}

4. 建造者模式(Builder)

        建造者模式用于创建复杂对象,它将对象的构造过程分解为若干个简单的步骤,从而使得用户可以更加灵活地创建对象。在Unity中,建造者模式常用于创建复杂的Prefab,例如角色或NPC。

以下是Builder模式的示例代码:

public class Character 
{
    private string _name;
    private string _gender;
    private string _race;
    private string _class;
    private int _level;
    private int _health;
    private int _mana;

    public string Name 
    {
        get { return _name; }
        set { _name = value; }
    }

    public string Gender 
    {
        get { return _gender; }
        set { _gender = value; }
    }

    public string Race 
    {
        get { return _race; }
        set { _race = value; }
    }

    public string Class 
    {
        get { return _class; }
        set { _class = value; }
    }

    public int Level 
    {
        get { return _level; }
        set { _level = value; }
    }

    public int Health 
    {
        get { return _health; }
        set { _health = value; }
    }

    public int Mana 
    {
        get { return _mana; }
        set { _mana = value; }
    }
}

public abstract class CharacterBuilder 
{
    protected Character _character;

    public Character Character 
    {
        get { return _character; }
    }

    public virtual void BuildName(string name) 
    {
        _character.Name = name;
    }

    public virtual void BuildGender(string gender)
    {
        _character.Gender = gender;
    }

    public virtual void BuildRace(string race) 
    {
        _character.Race = race;
    }

    public virtual void BuildClass(string className) 
    {
        _character.Class = className;
    }

    public virtual void BuildLevel(int level) 
    {
        _character.Level = level;
    }

    public virtual void BuildHealth(int health) 
    {
        _character.Health = health;
    }

    public virtual void BuildMana(int mana) 
    {
        _character.Mana = mana;
    }
}

public class HumanBuilder : CharacterBuilder 
{
    public HumanBuilder()
    {
        _character = new Character();
    }

    public override void BuildRace(string race)
    {
        if (race.Equals("Human"))
        {
            _character.Race = race;
        }
        else
        {
            throw new System.Exception("Invalid race for Human builder.");
        }
    }

    public override void BuildClass(string className)
    {
        if (className.Equals("Warrior") || className.Equals("Mage"))
        {
            _character.Class = className;
        }
        else
        {
            throw new System.Exception("Invalid class for Human builder.");
        }
    }
}

public class CharacterDirector 
{
    private CharacterBuilder _builder;

    public CharacterDirector(CharacterBuilder builder) 
    {
        _builder = builder;
    }

    public void Construct(string name, string gender, string race, string className, int level, int health, int mana) 
    {
        _builder.BuildName(name);
        _builder.BuildGender(gender);
        _builder.BuildRace(race);
        _builder.BuildClass(className);
        _builder.BuildLevel(level);
        _builder.BuildHealth(health);
        _builder.BuildMana(mana);
    }
}

5. 原型模式(Prototype)

        原型模式用于通过克隆的方式创建对象,它可以帮助我们避免重复实例化对象的开销。在Unity中,原型模式常用于场景中的复制和实例化对象,例如在场景中复制NPC或道具。

以下是Prototype模式的示例代码:

public abstract class Prototype 
{
    public string Type;

    public abstract Prototype Clone();
}

public class ConcretePrototypeA : Prototype 
{
    public ConcretePrototypeA() 
    {
        Type = "A";
    }

    public override Prototype Clone() 
    {
        return (Prototype)MemberwiseClone();
    }
}

public class ConcretePrototypeB : Prototype 
{
    public ConcretePrototypeB() 
    {
        Type = "B";
    }

    public override Prototype Clone()
    {
        return (Prototype)MemberwiseClone();
    }
}

public class PrototypeManager 
{
    private Dictionary<string, Prototype> _prototypes = new Dictionary<string, Prototype>();

    public Prototype this[string key]
    {
        get { return _prototypes[key].Clone(); }
        set { _prototypes.Add(key, value); }
    }
}

6. 外观模式(Facade)

        外观模式用于为复杂的子系统提供一个简单的接口。在Unity中,外观模式常用于将复杂的系统或流程封装起来,简化客户端的调用,例如场景管理器和资源管理器。

以下是Facade模式的示例代码:

public class SceneLoader 
{
    public void LoadScene(string sceneName) 
    {
        Debug.Log("Loading Scene " + sceneName);
    }
}

public class SoundManager
{
    public void PlaySound(string soundName) 
    {
        Debug.Log("Playing Sound " + soundName);
    }
}

public class ResourceManager 
{
    public void LoadResource(string resourceName) 
    {
        Debug.Log("Loading Resource " + resourceName);
    }
}

public class GameFacade 
{
    private SceneLoader _sceneLoader;
    private SoundManager _soundManager;
    private ResourceManager _resourceManager;

    public GameFacade() 
    {
        _sceneLoader = new SceneLoader();
        _soundManager = new SoundManager();
        _resourceManager = new ResourceManager();
    }

    public void StartGame(string sceneName, string soundName, string resourceName) 
    {
        _sceneLoader.LoadScene(sceneName);
        _soundManager.PlaySound(soundName);
        _resourceManager.LoadResource(resourceName);
    }
}

7. 适配器模式(Adapter)

        适配器模式用于将一个类的接口转换成客户端所期望的另一个接口。在Unity中,适配器模式常用于连接不同的API或组件。

以下是Adapter模式的示例代码:

public interface ITarget 
{
    void Request();
}

public class Adaptee 
{
    public void SpecificRequest() 
    {
        Debug.Log("Specific Request");
    }
}

public class Adapter : ITarget 
{
    private Adaptee _adaptee = new Adaptee();

    public void Request() 
    {
        _adaptee.SpecificRequest();
    }
}

8. 桥接模式(Bridge)

        桥接模式用于将抽象部分与实现部分分离,使它们可以独立地变化。在Unity中,桥接模式常用于将不同的场景、资源和组件分离,从而使它们可以独立地开发和管理。

下是Bridge模式的示例代码:

public abstract class Shape 
{
    protected IDrawAPI _drawAPI;

    protected Shape(IDrawAPI drawAPI) 
    {
        _drawAPI = drawAPI;
    }

    public abstract void Draw();
}

public interface IDrawAPI 
{
    void DrawCircle(int x, int y, int radius);
}

public class DrawAPI1 : IDrawAPI 
{
    public void DrawCircle(int x, int y, int radius) 
    {
        Debug.Log("DrawAPI1 Circle " + x + "," + y + "," + radius);
    }
}

public class DrawAPI2 : IDrawAPI 
{
    public void DrawCircle(int x, int y, int radius)
    {
        Debug.Log("DrawAPI2 Circle " + x + "," + y + "," + radius);
    }
}

public class Circle : Shape 
{
    private int _x, _y, _radius;

    public Circle(int x, int y, int radius, IDrawAPI drawAPI) : base(drawAPI) 
    {
        _x = x;
        _y = y;
        _radius = radius;
    }

    public override void Draw() 
    {
        _drawAPI.DrawCircle(_x, _y, _radius);
    }
}

9. 组合模式(Composite)

        组合模式将对象组合成树形结构以表示“部分-整体”的层次结构,在Unity中,组合模式常用于组织和管理场景中的对象,例如场景中的资源树和对象树。

以下是Composite模式的示例代码:

public abstract class Component 
{
    protected string _name;

    public Component(string name) 
    {
        _name = name;
    }

    public abstract void Add(Component component);
    public abstract void Remove(Component component);
    public abstract void Display(int depth);
}

public class Leaf : Component 
{
    public Leaf(string name) : base(name) 
    {
    }

    public override void Add(Component component) 
    {
        Debug.Log("Cannot add to a leaf.");
    }

    public override void Remove(Component component) 
    {
        Debug.Log("Cannot remove from a leaf.");
    }

    public override void Display(int depth) 
    {
        Debug.Log(new string('-', depth) + " " + _name);
    }
}

public classComposite : Component
{
private List<Component> _children = new List<Component>();
public Composite(string name) : base(name) 
{
}

public override void Add(Component component) 
{
    _children.Add(component);
}

public override void Remove(Component component) 
{
    _children.Remove(component);
}

public override void Display(int depth) 
{
    Debug.Log(new string('-', depth) + " " + _name);

    foreach (Component component in _children)
    {
        component.Display(depth + 2);
    }
}
}

10.装饰者模式(Decorator)

        装饰器模式用于动态地给一个对象添加一些额外的职责,而无需修改这个对象的代码。在Unity中,装饰器模式常用于对场景中的对象进行装饰,例如对NPC进行装饰以显示状态或属性。

以下是Decorator模式的示例代码:

public abstract class Component 
{
    public abstract void Operation();
}

public class ConcreteComponent : Component 
{
    public override void Operation() 
    {
        Debug.Log("Concrete Component Operation");
    }
}

public abstract class Decorator : Component 
{
    private Component _component;

    public Decorator(Component component) 
    {
        _component = component;
    }

    public override void Operation() 
    {
        if (_component != null) 
        {
            _component.Operation();
        }
    }
}

public class ConcreteDecoratorA : Decorator 
{
    public ConcreteDecoratorA(Component component) : base(component) 
    {
    }

    public override void Operation() 
    {
        base.Operation();
        AddedBehavior();
        Debug.Log("Concrete Decorator A Operation");
    }

    private void AddedBehavior() 
    {
        Debug.Log("Added Behavior from Concrete Decorator A");
    }
}

public class ConcreteDecoratorB : Decorator 
{
    public ConcreteDecoratorB(Component component) : base(component) 
    {
    }

    public override void Operation() 
    {
        base.Operation();
        AddedBehavior();
        Debug.Log("Concrete Decorator B Operation");
    }

    private void AddedBehavior() 
    {
        Debug.Log("Added Behavior from Concrete Decorator B");
    }
}

11. 处理者模式(Chain of Responsibility)

        处理者模式用于避免将请求发送方和接收方直接耦合在一起,从而让多个对象都有机会处理请求。在Unity中,处理者模式常用于处理输入事件和状态变化事件。

以下是Chain of Responsibility模式的示例代码:

public abstract class Handler 
{
    protected Handler _successor;

    public void SetSuccessor(Handler successor) 
    {
        _successor = successor;
    }

    public abstract void HandleRequest(int request);
}

public class ConcreteHandlerA : Handler 
{
    public override void HandleRequest(int request) 
    {
        if (request >= 0 && request < 10) 
        {
            Debug.Log("Handled by Concrete Handler A");
        }
        else if (_successor != null)
        {
            _successor.HandleRequest(request);
        }
    }
}

public class ConcreteHandlerB : Handler 
{
    public override void HandleRequest(int request) 
    {
        if (request >= 10 && request < 20) 
        {
            Debug.Log("Handled by Concrete Handler B");
        }
        else if (_successor != null)
        {
            _successor.HandleRequest(request);
        }
    }
}

public class ConcreteHandlerC : Handler 
{
    public override void HandleRequest(int request) 
    {
        if (request >= 20 && request < 30) 
        {
            Debug.Log("Handled by Concrete Handler C");
        }
        else if (_successor != null)
        {
            _successor.HandleRequest(request);
        }
    }
}

public class Client
{
private Handler _handlerChain;
public Client() 
{
    _handlerChain = new ConcreteHandlerA();
    Handler handlerB = new ConcreteHandlerB();
    Handler handlerC = new ConcreteHandlerC();
    _handlerChain.SetSuccessor(handlerB);
    handlerB.SetSuccessor(handlerC);
}

public void ProcessRequests() 
{
    int[] requests = new int[] { 2, 17, 25, 40, 5 };

    foreach (int request in requests)
    {
        _handlerChain.HandleRequest(request);
    }
}
}

12. 迭代器模式(Iterator)

        迭代器模式用于访问一个聚合对象中的所有元素,而不需要暴露其内部表示。在Unity中,迭代器模式常用于遍历列表、集合、字典等数据结构。

以下是Iterator模式的示例代码:

 

public interface IIterator<T> 
{
    bool HasNext();
    T Next();
}

public interface IAggregate<T> 
{
    IIterator<T> GetIterator();
}

public class ConcreteIterator<T> : IIterator<T> 
{
    private List<T> _items;
    private int _currentIndex = 0;

    public ConcreteIterator(List<T> items) 
    {
        _items = items;
    }

    public bool HasNext() 
    {
        return _currentIndex < _items.Count;
    }

    public T Next() 
    {
        T item = _items[_currentIndex];
        _currentIndex++;
        return item;
    }
}

public class ConcreteAggregate<T> : IAggregate<T> 
{
    private List<T> _items = new List<T>();

    public void AddItem(T item) 
    {
        _items.Add(item);
    }

    public IIterator<T> GetIterator() 
    {
        return new ConcreteIterator<T>(_items);
    }
}

13. 中介者模式(Mediator)

        中介者模式用于降低对象之间的耦合度,使其能够更好地协作。在Unity中,中介者模式常用于处理多个对象之间的交互,例如UI界面中的组件之间的交互。

以下是Mediator模式的示例代码:

public abstract class Colleague 
{
    protected IMediator _mediator;

    public Colleague(IMediator mediator) 
    {
        _mediator = mediator;
    }

    public abstract void Send(string message);
    public abstract void Receive(string message);
}

public interface IMediator 
{
    void AddColleague(Colleague colleague);
    void SendMessage(Colleague sender, string message);
}

public class ConcreteColleagueA : Colleague 
{
    public ConcreteColleagueA(IMediator mediator) : base(mediator) 
    {
    }

    public override void Send(string message) 
    {
        _mediator.SendMessage(this, message);
    }

    public override void Receive(string message) 
    {
        Debug.Log("Concrete Colleague A received message: " + message);
    }
}

public class ConcreteColleagueB : Colleague 
{
    public ConcreteColleagueB(IMediator mediator) : base(mediator) 
    {
    }

    public override void Send(string message) 
    {
        _mediator.SendMessage(this, message);
    }

    public override void Receive(string message) 
    {
        Debug.Log("Concrete Colleague B received message: " + message);
    }
}

public class ConcreteMediator : IMediator 
{
    private List<Colleague> _colleagues = new List<Colleague>();

    public void AddColleague(Colleague colleague) 
    {
        _colleagues.Add(colleague);
    }

    public void SendMessage(Colleague sender, string message) 
    {
        foreach (Colleague colleague in _colleagues)
        {
            if (colleague != sender)
            {
                colleague.Receive(message);
            }
        }
    }
}

14. 备忘录模式(Memento)

        备忘录模式用于将对象的状态保存下来,并在需要时进行恢复。在Unity中,备忘录模式常用于保存游戏的状态,例如玩家的进度或者游戏的设置。

以下是Memento模式的示例代码:

public class Memento 
{
    public int Level { get; private set; }
    public int Score { get; private set; }

    public Memento(int level, int score) 
    {
        Level = level;
        Score = score;
    }
}

public class Originator 
{
    public int Level { get; set; }
    public int Score { get; set; }

    public Memento Save() 
    {
        return new Memento(Level, Score);
    }

    public void Load(Memento memento) 
    {
        Level = memento.Level;
        Score = memento.Score;
    }
}

public class Caretaker 
{
    private Dictionary<string, Memento> _mementos = new Dictionary<string, Memento>();

    public void SaveState(string savepoint, Memento memento) 
    {
        _mementos.Add(savepoint, memento);
    }

    public Memento LoadState(string savepoint) 
    {
        if (!_mementos.ContainsKey(savepoint))
        {
            return null;
        }

        Memento memento = _mementos[savepoint];
        _mementos.Remove(savepoint);
        return memento;
    }
}

15. 观察者模式(Observer)

        观察者模式用于对象之间的一对多依赖关系,当一个对象的状态发生改变时,所有依赖于它的对象都会得到通知并自动更新。在Unity中,观察者模式常用于事件的处理和UI界面的更新。

以下是Observer模式的示例代码:

public interface IObserver 
{
    void Update(ISubject subject);
}

public interface ISubject 
{
    void Attach(IObserver observer);
    void Detach(IObserver observer);
    void Notify();
}

public abstract class Subject : ISubject 
{
    private List<IObserver> _observers = new List<IObserver>();

    public void Attach(IObserver observer) 
    {
        _observers.Add(observer);
    }

    public void Detach(IObserver observer) 
    {
        _observers.Remove(observer);
    }

    public void Notify() 
    {
        foreach (IObserver observer in _observers)
        {
            observer.Update(this);
        }
    }
}

public class ConcreteSubject : Subject 
{
    private string _state;

    public string State 
    {
        get 
        {
            return _state;
        }
        set 
        {
            _state = value;
            Notify();
        }
    }
}

public class ConcreteObserver : IObserver 
{
    private string _observerState;

    public void Update(ISubject subject) 
    {
        if (subject is ConcreteSubject)
        {
            ConcreteSubject concreteSubject = (ConcreteSubject)subject;
            _observerState = concreteSubject.State;
            Debug.Log("Observer State: " + _observerState);
        }
    }
}

16. 访问者模式(Visitor)

        访问者模式用于对对象结构中的元素进行操作,并在不改变类的前提下添加新的操作。在Unity中,访问者模式可用于遍历游戏对象并对其进行操作,例如在场景中添加特效或改变材质。

以下是Visitor模式的示例代码:

public interface IVisitor 
{
    void Visit(ConcreteElementA element);
    void Visit(ConcreteElementB element);
}

public abstract class Element 
{
    public abstract void Accept(IVisitor visitor);
}

public class ConcreteElementA : Element 
{
    public override void Accept(IVisitor visitor) 
    {
        visitor.Visit(this);
    }

    public string OperationA() 
    {
        return "Concrete Element A Operation";
    }
}

public class ConcreteElementB : Element 
{
    public override void Accept(IVisitor visitor) 
    {
        visitor.Visit(this);
    }

    public string OperationB() 
    {
        return "Concrete Element B Operation";
    }
}

public class ConcreteVisitor : IVisitor 
{
    public void Visit(ConcreteElementA element) 
    {
        Debug.Log(element.OperationA());
    }

    public void Visit(ConcreteElementB element) 
    {
        Debug.Log(element.OperationB());
    }
}

public class ObjectStructure 
{
    private List<Element> _elements = new List<Element>();

    public void AddElement(Element element) 
    {
        _elements.Add(element);
    }

    public void RemoveElement(Element element) 
    {
        _elements.Remove(element);
    }

    public void Accept(IVisitor visitor) 
    {
        foreach (Element element in _elements)
        {
            element.Accept(visitor);
        }
    }
}

17. 状态模式(State)

        状态模式用于根据对象的状态改变其行为,并将状态的处理逻辑封装在状态类中。在Unity中,状态模式常用于处理游戏对象的状态转换,例如角色的不同状态(站立、走动、跳跃)。

以下是State模式的示例代码:

public interface IState 
{
    void HandleState(Context context);
}

public class ConcreteStateA : IState 
{
    public void HandleState(Context context) 
    {
        Debug.Log("Handle State A");
        context.State = new ConcreteStateB();
    }
}

public class ConcreteStateB : IState 
{
    public void HandleState(Context context) 
    {
        Debug.Log("Handle State B");
        context.State = new ConcreteStateA();
    }
}

public class Context 
{
    public IState State { get; set; }

    public Context(IState state) 
    {
        State = state;
    }

    public void Request() 
    {
        State.HandleState(this);
    }
}

18. 策略模式(Strategy)

        策略模式定义了一系列算法,并将每个算法封装起来,使其可以互换使用。在Unity中,策略模式常用于处理游戏中的不同操作,例如角色的战斗决策(攻击、防御、逃跑)。

以下是Strategy模式的示例代码:

public interface IStrategy 
{
    void Execute();
}

public class ConcreteStrategyA : IStrategy 
{
    public void Execute() 
    {
        Debug.Log("Execute Strategy A");
    }
}

public class ConcreteStrategyB : IStrategy 
{
    public void Execute() 
    {
        Debug.Log("Execute Strategy B");
    }
}

public class Context 
{
    private IStrategy _strategy;

    public Context(IStrategy strategy) 
    {
        _strategy = strategy;
    }

    public void SetStrategy(IStrategy strategy) 
    {
        _strategy = strategy;
    }

    public void DoAction() 
    {
        _strategy.Execute();
    }
}

19. 命令模式(Command)

        命令模式用于将操作封装在对象中,并将其它对象请求操作的对象进行解耦。在Unity中,命令模式常用于处理游戏中的操作,例如角色的移动、攻击等。

以下是Command模式的示例代码:

public interface ICommand 
{
    void Execute();
    void Undo();
}

public class MoveCommand : ICommand 
{
    private Transform _transform;
    private Vector3 _direction;

    public MoveCommand(Transform transform, Vector3 direction) 
    {
        _transform = transform;
        _direction = direction;
    }

    public void Execute() 
    {
        _transform.position += _direction; // 移动对象
    }

    public void Undo() 
    {
        _transform.position -= _direction; // 撤销移动
    }
}

public class AttackCommand : ICommand 
{
    private GameObject _target;

    public AttackCommand(GameObject target) 
    {
        _target = target;
    }

    public void Execute() 
    {
        _target.GetComponent<Enemy>().TakeDamage(); // 攻击目标
    }

    public void Undo() 
    {
        _target.GetComponent<Enemy>().Heal(); // 撤销攻击
    }
}

public class CommandInvoker 
{
    private Stack<ICommand> _commands = new Stack<ICommand>();

    public void AddCommand(ICommand command) 
    {
        _commands.Push(command);
        command.Execute();
    }

    public void UndoLastCommand() 
    {
        if (_commands.Count > 0)
        {
            ICommand command = _commands.Pop();
            command.Undo();
        }
    }
}

20. 解释器模式(Interpreter)

        解释器模式用于对语言进行解释,并将其转换成计算机可以处理的形式。在Unity中,解释器模式不常用。

以下是Interpreter模式的示例代码:

public abstract class AbstractExpression 
{
    public abstract double Interpret();
}

public class NumberExpression : AbstractExpression 
{
    private double _number;

    public NumberExpression(double number) 
    {
        _number = number;
    }

    public override double Interpret() 
    {
        return _number;
    }
}

public class AdditionExpression : AbstractExpression 
{
    private AbstractExpression _expression1;
    private AbstractExpression _expression2;

    public AdditionExpression(AbstractExpression expression1, AbstractExpression expression2) 
    {
        _expression1 = expression1;
        _expression2 = expression2;
    }

    public override double Interpret() 
    {
        return _expression1.Interpret() + _expression2.Interpret();
    }
}

public class SubtractionExpression : AbstractExpression 
{
    private AbstractExpression _expression1;
    private AbstractExpression _expression2;

    public SubtractionExpression(AbstractExpression expression1, AbstractExpression expression2) 
    {
        _expression1 = expression1;
        _expression2 = expression2;
    }

    public override double Interpret() 
    {
        return _expression1.Interpret() - _expression2.Interpret();
    }
}

public class MultiplicationExpression : AbstractExpression 
{
    private AbstractExpression _expression1;
    private AbstractExpression _expression2;

    public MultiplicationExpression(AbstractExpression expression1, AbstractExpression expression2) 
    {
        _expression1 = expression1;
        _expression2 = expression2;
    }

    public override double Interpret() 
    {
        return _expression1.Interpret() * _expression2.Interpret();
    }
}

public class DivisionExpression : AbstractExpression 
{
    private AbstractExpression _expression1;
    private AbstractExpression _expression2;

    public DivisionExpression(AbstractExpression expression1, AbstractExpression expression2) 
    {
        _expression1 = expression1;
        _expression2 = expression2;
    }

    public override double Interpret() 
    {
        return _expression1.Interpret() / _expression2.Interpret();
    }
}

public class Interpreter 
{
    public static void Test() 
    {
        AbstractExpression expression = new AdditionExpression(
            new NumberExpression(5), 
            new MultiplicationExpression(
                new NumberExpression(10),
                new SubtractionExpression(
                    new NumberExpression(8),
                    new NumberExpression(2)
                )
            )
        );

        double result = expression.Interpret();
        Debug.Log("Interpreter result: " + result);
    }
}

21. 享元模式(Flyweight)

        享元模式用于减少系统中对象的数量,并且可以提高系统的性能。在Unity中,享元模式常用于优化游戏中大量的重复性质的对象,例如粒子、模型等。

以下是Flyweight模式的示例代码:

public class Flyweight 
{
    private string _state;

    public Flyweight(string state) 
    {
        _state = state;
    }

    public void Operation() 
    {
        Debug.Log("Flyweight operation with state: " + _state);
    }
}

public class FlyweightFactory 
{
    private Dictionary<string, Flyweight> _flyweights = new Dictionary<string, Flyweight>();

    public Flyweight GetFlyweight(string key) 
    {
        if (!_flyweights.ContainsKey(key))
        {
            _flyweights.Add(key, new Flyweight(key));
        }

        return _flyweights[key];
    }
}

22. 责任链模式(Chain of Responsibility)

        责任链模式用于在多个对象中处理一个请求时,将请求沿着对象链传递,直到有一个对象处理为止。在Unity中,责任链模式常用于处理游戏中的输入事件、UI事件等。

以下是Chain of Responsibility模式的示例代码:

public abstract class Handler 
{
    private Handler _nextHandler;

    public Handler NextHandler 
    {
        get 
        {
            return _nextHandler;
        }
        set 
        {
            _nextHandler = value;
        }
    }

    public abstract void HandleRequest(int request);
}

public class ConcreteHandlerA : Handler 
{
    public override void HandleRequest(int request) 
    {
        if (request < 0)
        {
            Debug.Log("Negative request handled by Handler A");
        }
        else if (NextHandler != null)
        {
            NextHandler.HandleRequest(request);
        }
    }
}

public class ConcreteHandlerB : Handler 
{
    public override void HandleRequest(int request) 
    {
        if (request > 100)
        {
            Debug.Log("Request > 100 handled by Handler B");
        }
        else if (NextHandler != null)
        {
            NextHandler.HandleRequest(request);
        }
    }
}

public class ChainOfResponsibilityTest 
{
    public static void Test() 
    {
        var handlerA = new ConcreteHandlerA();
        var handlerB = new ConcreteHandlerB();

        handlerA.NextHandler = handlerB;

        handlerA.HandleRequest(-1); // handled by Handler A
        handlerA.HandleRequest(50); // not handled
        handlerA.HandleRequest(150); // handled by Handler B
    }
}

23. 模板方法模式(Template Method)

        模板方法模式用于定义一个算法的骨架,而将一些步骤实现留给子类来完成。在Unity中,模板方法模式常用于处理游戏中的流程、关卡等。

以下是Template Method模式的示例代码:

public abstract class AbstractClass 
{
    public void TemplateMethod() 
    {
        Operation1();
        Operation2();
        Operation3();
    }

    protected abstract void Operation1();
    protected abstract void Operation2();
    protected abstract void Operation3();
}

public class ConcreteClass : AbstractClass 
{
    protected override void Operation1() 
    {
        Debug.Log("Operation 1");
    }

    protected override void Operation2() 
    {
        Debug.Log("Operation 2");
    }

    protected override void Operation3() 
    {
        Debug.Log("Operation 3");
    }
}

public class TemplateMethodTest 
{
    public static void Test() 
    {
        AbstractClass obj = new ConcreteClass();
        obj.TemplateMethod();
    }
}

在软件开发中,设计模式是一种常用的编程思想,它提供了在不同场景下的不同解决方案,可以使我们的代码更加灵活、可扩展、维护性更好。本文介绍了23种常用的设计模式,包括创建型模式、结构型模式和行为型模式。这些模式都经过实践验证,可以提供良好的参考和指导,帮助你更好地设计和实现高质量的软件。在实际开发中,我们可以结合具体场景选择合适的设计模式,以达到更好的效果。