zoukankan      html  css  js  c++  java
  • 设计模式:简单工厂

             简单工厂的作用是实例化对象,而不需要客户了解这个对象属于哪个具体的子类。

             简单工厂实例化的类具有相同的接口,在类有限并且基本不需要扩展时,可以使用简单工厂。例如,数据库连接对象,常用的数据库类类可以预知,则使用简单工厂。
              采用简单工厂的优点是可以使用户根据参数获得对应的类实例,避免了直接实例化类,降低了耦合性;缺点是可实例化的类型在编译期间已经被确定,如果增加新类型,则需要修改工厂,不符合OCP的原则。简单工厂需要知道所有要生成的类型,当子类过多或者子类层次过多时不适合使用。

    image

    namespace DP
    {
        class Client
        {
            static void Main(string[] args)
            {
                // 避免了这里对Sugar类的直接依赖
                IFood food = FoodShop.Sale("Sugar");
              food.Eat();
        
                // 避免了这里对Bread类的直接依赖
                food = FoodShop.Sale("Bread");
               food.Eat();
               Console.Read();
            }
        }
        
        public interface IFood
        {
            void Eat();
        }
        
        public class Bread : IFood
        {
        
            public void Eat()
            {
                Console.WriteLine("Bread is delicious!");
            }
        }
        
        public class Sugar : IFood
        {
        
            public void Eat()
            {
                Console.WriteLine("Sugar is delicious!");
            }
        }
        
        public class FoodShop
        {
            public static IFood Sale(string foodName)
            {
                switch (foodName)
                {
                    case "Sugar":
                        return new Sugar();                    
                    case "Bread":
                        return new Bread();
                    default:
                        throw new ArgumentException();                    
                }
            }
        }    
    }
  • 相关阅读:
    有7g和2g的砝码各一个,怎样称可以3次把140g东西分为50g和90g???????
    中缀到后缀(一个例子)
    动态代理模式的使用
    代理模式用来初始化的延迟下载
    ReentrantLock Condition 实现消费者生产者问题
    Two Sum
    [leetcode]重建二叉树(先序和终须) 中序遍和后续
    (转载)旋转数组查找 最简洁方法 总结
    [不明觉厉] 下一个排列
    codeforces -- 283A
  • 原文地址:https://www.cnblogs.com/cnblogsfans/p/1611288.html
Copyright © 2011-2022 走看看