代码改变世界

设计模式:简单工厂

2009-11-26 13:47  敏捷的水  阅读(490)  评论(0编辑  收藏  举报

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

         简单工厂实例化的类具有相同的接口,在类有限并且基本不需要扩展时,可以使用简单工厂。例如,数据库连接对象,常用的数据库类类可以预知,则使用简单工厂。
          采用简单工厂的优点是可以使用户根据参数获得对应的类实例,避免了直接实例化类,降低了耦合性;缺点是可实例化的类型在编译期间已经被确定,如果增加新类型,则需要修改工厂,不符合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();                    
            }
        }
    }    
}