代码改变世界

抽象工厂

  Clingingboy  阅读(704)  评论(0编辑  收藏  举报

  提供一个创建一系列相关或相互依赖对象的接口,而无需指定它们具体的类

image_2

对于不同类产品提供一类工厂

1.产品接口

interface IBag {
   string Material { get; }
 }
 
 // Product 2
 interface IShoes {
   int Price { get; }
 }


2.工厂

这里采用了泛型,所以会更灵活些

interface IFactory<Brand>
   where Brand : IBrand {
   IBag CreateBag();
   IShoes CreateShoes();
 }
 
 // Conctete Factories (both in the same one)
 class Factory<Brand> : IFactory<Brand>
   where Brand : IBrand, new() {
   public IBag CreateBag() {
     return new Bag<Brand>();
   }
 
   public IShoes CreateShoes() {
     return new Shoes<Brand>();
   }
 }


3.IBrand

不同类产品信息

interface IBrand {
   int Price { get; }
   string Material { get; }
 }
 
 class Gucci : IBrand {
   public int Price { get { return 1000; } }
   public string Material { get { return "Crocodile skin"; } }
 }
 
 class Poochy : IBrand {
   public int Price { get { return new Gucci().Price / 3; } }
   public string Material { get { return "Plastic"; } }
 }
 
 class Groundcover : IBrand {
   public int Price { get { return 2000; } }
   public string Material { get { return "South african leather"; } }
 }

4.对不同类产品创建不同工厂

class Client<Brand>
     where Brand : IBrand, new() {
     public void ClientMain() { //IFactory<Brand> factory)
       IFactory<Brand> factory = new Factory<Brand>();
 
       IBag bag = factory.CreateBag();
       IShoes shoes = factory.CreateShoes();
 
       Console.WriteLine("I bought a Bag which is made from " + bag.Material);
       Console.WriteLine("I bought some shoes which cost " + shoes.Price);
       Console.ReadKey();
     }
   }
 
   static class Program {
     static void Main() {
       // Call Client twice
       new Client<Poochy>().ClientMain();
       new Client<Gucci>().ClientMain();
       new Client<Groundcover>().ClientMain();
     }
   }

此模式应该来说非常重要,应用也比较广泛.结合反射功能效果会更好.

编辑推荐:
· AI与.NET技术实操系列:基于图像分类模型对图像进行分类
· go语言实现终端里的倒计时
· 如何编写易于单元测试的代码
· 10年+ .NET Coder 心语,封装的思维:从隐藏、稳定开始理解其本质意义
· .NET Core 中如何实现缓存的预热?
阅读排行:
· 分享一个免费、快速、无限量使用的满血 DeepSeek R1 模型,支持深度思考和联网搜索!
· 25岁的心里话
· 基于 Docker 搭建 FRP 内网穿透开源项目(很简单哒)
· ollama系列01:轻松3步本地部署deepseek,普通电脑可用
· 按钮权限的设计及实现
历史上的今天:
2009-08-26 Spring.NET学习笔记(6)-基础AOP
点击右上角即可分享
微信分享提示