asp.net mvc 学习笔记 - 单一实例设计模式
学习之前,先喊一下口号:每天进步一点,生活更好一点
首先声明一点,我也是新新新手一枚,崭新的新哦。如果文章有不合理的地方,也请各位博友多多指点,不要乱喷哦
我的文采很低调,低调到语文老师对我的期望是你什么时候能及格啊!!!▄█▀█●给跪了@@@ 所以我的文章都是直奔主题,没有华丽的装饰,没准可以美而言之『通俗易懂』呢ヾ(=゚・゚=)ノ喵♪
好了,可以开始了
我们声明两个类 Customer 和 Order
- public class Customer
- {
- public string CustomerID { get; set; }
- public string CompanyName { get; set; }
- public string ContactName { get; set; }
- public string ContactTitle { get; set; }
- }
- public class Order
- {
- public int OrderID { get; set; }
- public string CustomerID { get; set; }
- public int? EmployeeId { get; set; }
- public DateTime? OrderDate { get; set; }
- }
如果是刚开始学习编程,如果要对这两个类进行操作,就需要建立两个操作类 CustomerOperation 和 OrderOperation
- public class CustomerOperation
- {
- public void Creat(Customer item)
- {
- }
- public void Delete(Customer item)
- {
- }
- public IEnumerable<Customer> Get()
- {
- }
- public void Update(Customer item)
- {
- }
- }
- public class OrderOperation
- {
- public void Creat(Order item)
- {
- }
- public void Delete(Order item)
- {
- }
- public IEnumerable<Order> Get()
- {
- }
- public void Update(Order item)
- {
- }
- }
好了,关于两个类的CRUD(增查改删)就写好了,下面我们就可以使用了
- static void Main(string[] args)
- {
- CustomerOperation customer = new CustomerOperation();
- OrderOperation order = new OrderOperation();
- customer.Get();
- order.Get();
- Console.ReadLine();
- }
这样一来,我们就new了两个实例,如果我们有一百个类,岂不是要new一百遍!!o(>﹏<)o
那怎么样new一个实例,可以同时操作两个类呢,那还不简单,我们把两个操作类,写到一个里边
- public class Factory
- {
- public void CustomerCreat(Customer item)
- {
- }
- public void CustomerDelete(Customer item)
- {
- }
- public IEnumerable<Customer> CustomerGet()
- {
- }
- public void CustomerUpdate(Customer item)
- {
- }
- public void OrderCreat(Order item)
- {
- }
- public void OrderDelete(Order item)
- {
- }
- public IEnumerable<Order> OrderGet()
- {
- }
- public void OrderUpdate(Order item)
- {
- }
- }
这时,我们再使用的时候,不就直接实例化一个就可以了
- static void Main(string[] args)
- {
- Factory factory = new Factory();
- Factory.CustomerGet();
- Factory.OrderGet();
- Console.ReadLine();
- }
果然聪明,这就基本上可以称作是单一实例模式了
但是,如果将来有一百个类,你的Factory岂不是要爆掉,那怎么办呢,我已经修炼了第一层功力,我是这样做的
原来的两个操作类不变,在Factory里边进行实例化
- public class Factory
- {
- private CustomerOperation _customerOperation = null;
- private OrderOperation _orderOperation = null;
- public Customer Customers
- {
- get
- {
- if (_customerOperation == null)
- {
- _customerOperation = new CustomerOperation();
- }
- return this._customerOperation;
- }
- }
- public Order Orders
- {
- get
- {
- if (_orderOperation == null)
- {
- _orderOperation = new OrderOperation();
- }
- return this._orderOperation;
- }
- }
- }
然后我们再去使用的时候
- static void Main(string[] args)
- {
- Factory factory = new Factory();
- factory .Orders.Get();
- factory .Customers.Get();
- Console.ReadLine();
- }
这样操作起来是不是就直观很多了,代码量也减少了很多,这就是我理解的单一实例模式