自学内容网 自学内容网

【C#设计模式(3)——抽象工厂模式(Abstract Factory Pattern)】

前言

抽象工厂模式(Abstract Factory Pattern)

运行结果

在这里插入图片描述

代码

//水果罐头接口
public interface IFruitCan
{
    void CreateCan();
}
//苹果罐头类
public class AppleCan : IFruitCan
{
    string Name { get; set; } = "苹果罐头";
    public void CreateCan()
    {
        Console.WriteLine($"生产了{Name}");
    }
}
//荔枝罐头类
public class LitchiCan : IFruitCan
{
    string Name { get; set; } = "黄桃罐头";
    public void CreateCan()
    {
        Console.WriteLine($"生产了{Name}");
    }
}
//蔬菜罐头接口
public interface IVegetableCan
{
    void CreateCan();
}
//菠菜罐头
public class SpinachCan : IVegetableCan
{
    string Name { get; set; } = "菠菜罐头";
    public void CreateCan()
    {
        Console.WriteLine($"生产了{Name}");
    }
}
//大豆罐头
public class SoybeanCan : IVegetableCan
{
    string Name { get; set; } = "黄豆罐头";
    public void CreateCan()
    {
        Console.WriteLine($"生产了{Name}");
    }
}
//抽象工厂
public interface ICanFactory
{
    IFruitCan CreateFruitCan();
    IVegetableCan CreateVegetableCan();
}
// 具体工厂1
public class GuangZhouCanFactory : ICanFactory
{
    public string Name { get; set; } = "广州罐头厂";
    public GuangZhouCanFactory(string name)
    {
        Name = name;
        Console.WriteLine($"{Name}正在生产......");
    }
    public IFruitCan CreateFruitCan()
    {
        return new AppleCan();
    }

    public IVegetableCan CreateVegetableCan()
    {
        return new SpinachCan();
    }
}
// 具体工厂2
public class ShangHaiCanFactory : ICanFactory
{
    public string Name { get; set; } = "上海罐头厂";
    public ShangHaiCanFactory(string name)
    {
        Name = name;
        Console.WriteLine($"{Name}正在生产......");
    }
    public IFruitCan CreateFruitCan()
    {
        return  new LitchiCan();
    }

    public IVegetableCan CreateVegetableCan()
    {
        return new SoybeanCan();
    }
}

/*
 * 抽象工厂模式:Abstract Factory Pattern
 */
internal class Program
{
    static void Main(string[] args)
    {
        //创建工厂实例
        ICanFactory factoryA = new GuangZhouCanFactory("广州罐头厂");
        //罐头实例
        IFruitCan fruitCanA = factoryA.CreateFruitCan();
        IVegetableCan vegetableCanA = factoryA.CreateVegetableCan();
        //方法
        fruitCanA.CreateCan();
        vegetableCanA.CreateCan();

        ICanFactory factoryB = new ShangHaiCanFactory("上海罐头厂");
        IFruitCan fruitCanB = factoryB.CreateFruitCan();
        IVegetableCan vegetableCanB = factoryB.CreateVegetableCan();
        fruitCanB.CreateCan();
        vegetableCanB.CreateCan();

        Console.ReadLine();
    }
}

原文地址:https://blog.csdn.net/weixin_43626218/article/details/143690059

免责声明:本站文章内容转载自网络资源,如本站内容侵犯了原著者的合法权益,可联系本站删除。更多内容请关注自学内容网(zxcms.com)!