前言
抽象工厂模式(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();
}
}
标签:设计模式,IFruitCan,Name,C#,Pattern,IVegetableCan,CreateCan,public,string
From: https://blog.csdn.net/weixin_43626218/article/details/143690059