码迷,mamicode.com
首页 > 其他好文 > 详细

34、面向对象设计模式之工厂模式——简单工厂模式与工厂方法模式比较

时间:2020-06-18 21:26:39      阅读:55      评论:0      收藏:0      [点我收藏+]

标签:ice   style   string   工厂模式   设计模式   方法   比较   ogr   null   

用下面的例子比较:

  

using System;

namespace LearnObject
{
    public class LeiFeng
    {
        public void Sweep()
        {
            Console.WriteLine("扫地");
        }
        public void Wash()
        {
            Console.WriteLine("洗衣服");
        }

        public void BuyRice()
        {
            Console.WriteLine("买米");
        }
    }
    public class Undergrade : LeiFeng
    {

    }

    public class Volunteer : LeiFeng
    {

    }

    public class SimpleLeiFengFactory
    {
        public static LeiFeng CreateLeiFeng(string typeName)
        {
            LeiFeng result = null;
            switch (typeName)
            {
                case "学雷锋的大学生":
                    result = new Undergrade();
                    break;
                case "社区志愿者":
                    result = new Volunteer();
                    break;
            }
            return result;
        }
    }
    public interface IFactory
    {
        LeiFeng CreateLeiFeng();
    }
    public class UndergradeFactory : IFactory
    {
        public LeiFeng CreateLeiFeng()
        {
            return new Undergrade();
        }
    }
    public class VolunteerFactory : IFactory
    {
        public LeiFeng CreateLeiFeng()
        {
            return new Volunteer();
        }
    }
    public class Program
    {
        public static void Main(string[] args)
        {
            // 不使用工厂实例化
            LeiFeng zhangsan = new Undergrade();
            zhangsan.BuyRice();
            zhangsan.Sweep();
            zhangsan.Wash();
            LeiFeng student1 = new Undergrade();
            student1.BuyRice();
            student1.Sweep();
            student1.Wash();

            //简单工厂实例化
            LeiFeng studentA = SimpleLeiFengFactory.CreateLeiFeng("学雷锋的大学生");
            studentA.BuyRice();
            studentA.Sweep();
            studentA.Wash();

            LeiFeng volunteer = SimpleLeiFengFactory.CreateLeiFeng("社区志愿者");
            volunteer.BuyRice();
            volunteer.Sweep();
            volunteer.Wash();

            //工厂方法实例化
            IFactory factory = new UndergradeFactory();
            LeiFeng student = factory.CreateLeiFeng();
            student.BuyRice();
            student.Sweep();
            student.Wash();
            factory = new VolunteerFactory();
            LeiFeng volunteer1 = factory.CreateLeiFeng();
            volunteer1.BuyRice();
            volunteer1.Sweep();
            volunteer1.Wash();
        }
    }
}

  

34、面向对象设计模式之工厂模式——简单工厂模式与工厂方法模式比较

标签:ice   style   string   工厂模式   设计模式   方法   比较   ogr   null   

原文地址:https://www.cnblogs.com/sy-liu/p/13159591.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!