设计模式--享元模式

2023-07-10 08:53:22 浏览数 (1)

享元模式是一种结构型设计模式,旨在通过共享对象来减少内存使用和提高性能。在享元模式中,相似对象被视为可以共享的对象,并由一个工厂对象统一管理。

以下是一个C#版的享元模式实现:

首先,我们定义一个接口IFlyweight,该接口定义了可以共享的对象的公共方法:

代码语言:javascript复制
public interface IFlyweight
{
    void Operation();
}

然后,我们定义一个具体享元Flyweight类,该类实现IFlyweight接口并包含一些状态(可共享的信息)。在本例中,我们将使用名字作为内部状态:

代码语言:javascript复制
public class ConcreteFlyweight : IFlyweight
{
    private string _name;

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

    public void Operation()
    {
        Console.WriteLine($"ConcreteFlyweight: {_name}");
    }
}

接下来,我们实现享元工厂FlyweightFactory类,该类维护一个字典,用于存储生成的共享对象。在本例中,我们的FlyweightFactory类将以名字作为参数,并返回具有相同名字的ConcreteFlyweight对象:

代码语言:javascript复制
public class FlyweightFactory
{
    private Dictionary<string, IFlyweight> _flyweights = new Dictionary<string, IFlyweight>();

    public IFlyweight GetFlyweight(string name)
    {
        if (_flyweights.TryGetValue(name, out IFlyweight flyweight))
        {
            Console.WriteLine("Flyweight already exists.");
            return flyweight;
        }
        else
        {
            flyweight = new ConcreteFlyweight(name);
            _flyweights.Add(name, flyweight);
            return flyweight;
        }
    }
}

最后,我们可以使用享元工厂FlyweightFactory来获取ConcreteFlyweight对象。在本例中,我们将尝试获取三个名字为“John”、“Jane”和“Bob”的ConcreteFlyweight对象,并调用它们的操作方法:

代码语言:javascript复制
var factory = new FlyweightFactory();

var flyweight1 = factory.GetFlyweight("John");
flyweight1.Operation();

var flyweight2 = factory.GetFlyweight("Jane");
flyweight2.Operation();

var flyweight3 = factory.GetFlyweight("Bob");
flyweight3.Operation();

输出:

代码语言:javascript复制
ConcreteFlyweight: John
ConcreteFlyweight: Jane
ConcreteFlyweight: Bob

【小结】

持续精进,自我迭代。

0 人点赞