简单工厂模式+泛型

雨燕双飞 提交于 2019-12-04 18:08:53

简单工厂模式 UML:

 

1.我们首先定义一个工厂模式的核心逻辑类:ProductFactoryClass,

2.然后抽象产品类:ProductClass1,ProductClass2

3.接口:IProduct

 没啥好说的 直接贴代码吧:

1.外部调用时:

1             SimpleFactory<Product1> product = new SimpleFactory<Product1>();
2             product.CreateShow().Product(20,200);

2.入口:

 1    /// <summary>
 2     /// 简单工厂 的实现层 
 3     /// </summary>
 4     public class SimpleFactory<T> where T : new()
 5     {
 6         private static T _instance;     
 7         public  T CreateShow()
 8         {
 9             if (_instance == null)     
10             {
11                 _instance = new T();   
12             }
13             return _instance;
14         }
15     }

3.抽象商品类:

 1     public class Product1 : IProduct
 2     {
 3         public void Product(int count, double price)
 4         {
 5             Console.WriteLine("Total:{0}", count * price);
 6             Console.ReadKey();
 7         }
 8     }
 9     public class Product2: IProduct
10     {
11         public void Product(int count, double price)
12         {
13             Console.WriteLine("Total:{0}", count * price*2);
14             Console.ReadKey();
15         }
16     }

4.接口:

1     public interface IProduct
2     {
3         public void Product(int days, double price);
4     }

 

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!