c#笔记--常规实现:单例、观察者模式

本文详细介绍了两种常见的设计模式——单例模式和观察者模式。在单例模式中,展示了两种实现方式,确保类只有一个实例并提供全局访问点。观察者模式则通过事件池和监听器实现订阅-发布机制,方便组件之间的通信。文章提供了完整的代码示例,便于理解这两种模式的实际运用。
摘要由CSDN通过智能技术生成

单例模式

public class Manager
{
	public static Manager Instance { private set; get; }  //方式1
}
public class Manager
{
    private static Manager _instance;
    public static Manager Instance => _instance ?? (_instance = new Manager()); //方式2
    /*方式2相当于:
    public static Manager Instance  
    {
        get
        {//lazy binding
            if(_instance == null)
                _instance = new Manager();
            return _instance;
        }
    }*/
}

观察者模式

using System.Collections.Generic; //Dictionary
using System;  //Action

public static class EventManager
{
    public static Dictionary<string, Action> EventPool = new Dictionary<string, Action>();

    public void AddListener(string eventName, Action listener)
    {
        if (!EventPool.TryGetValue(eventName, out Action action))
        {
            action += listener;
            EventPool.Add(eventName, action);
            return;
        }
        EventPool[eventName] += listener;
    }

    public void RemoveListener(string eventName, Action listener)
    {
        if (EventPool.TryGetValue(eventName, out Action action))
        {
            if (EventPool[eventName] != null)
                EventPool[eventName] -= listener;
        }
        else throw new Exception($"Event {eventName} is not in EventPool");
    }

    public void Broadcast(string eventName)
    {
        if (EventPool.TryGetValue(eventName, out Action action))
        {
            action?.Invoke();
        }
    }

    public void Clear(string eventName)
    {
        if (EventPool.TryGetValue(eventName, out Action action))
        {
            EventPool[eventName] = null;
        }
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值