.Net 几种常用设计模式【工厂、单例】

发布时间 2023-12-28 11:57:57作者: WantRemake
抽象工厂模式
//
抽象产品 public interface IProduct { void Operation(); } // 具体产品A public class ProductA : IProduct { public void Operation() { Console.WriteLine("Product A Operation"); } } // 具体产品B public class ProductB : IProduct { public void Operation() { Console.WriteLine("Product B Operation"); } } // 抽象工厂 public interface IFactory { IProduct CreateProduct(); } // 具体工厂A public class FactoryA : IFactory { public IProduct CreateProduct() { return new ProductA(); } } // 具体工厂B public class FactoryB : IFactory { public IProduct CreateProduct() { return new ProductB(); } } // 客户端 public class Client { private IFactory factory; public Client(IFactory factory) { this.factory = factory; } public void Run() { IProduct product = factory.CreateProduct(); product.Operation(); } } // 使用示例 IFactory factoryA = new FactoryA(); Client clientA = new Client(factoryA); clientA.Run(); IFactory factoryB = new FactoryB(); Client clientB = new Client(factoryB); clientB.Run();
简单工厂模式
// 抽象产品
public interface IProduct
{
    void Operation();
}

// 具体产品A
public class ProductA : IProduct
{
    public void Operation()
    {
        Console.WriteLine("Product A Operation");
    }
}

// 具体产品B
public class ProductB : IProduct
{
    public void Operation()
    {
        Console.WriteLine("Product B Operation");
    }
}

// 工厂
public class SimpleFactory
{
    public IProduct CreateProduct(string type)
    {
        switch (type)
        {
            case "A":
                return new ProductA();
            case "B":
                return new ProductB();
            default:
                throw new ArgumentException("Invalid product type");
        }
    }
}

// 客户端
public class Client
{
    private SimpleFactory factory;

    public Client(SimpleFactory factory)
    {
        this.factory = factory;
    }

    public void Run()
    {
        IProduct product = factory.CreateProduct("A");
        product.Operation();
    }
}

// 使用示例
SimpleFactory simpleFactory = new SimpleFactory();
Client client = new Client(simpleFactory);
client.Run();
单例模式
public sealed class Singleton
{
    private static readonly Singleton instance = new Singleton();

    private Singleton()
    {
    }

    public static Singleton Instance
    {
        get
        {
            return instance;
        }
    }

    public void Operation()
    {
        Console.WriteLine("Singleton Operation");
    }
}

// 客户端
public class Client
{
    public void Run()
    {
        Singleton instance = Singleton.Instance;
        instance.Operation();
    }
}

// 使用示例
Client client = new Client();
client.Run();

转载自:https://blog.51cto.com/u_16175525/6778901