34面向对象设计模式之工厂模式——简单工厂模式与工厂方法模式比较
Posted sy-liu
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了34面向对象设计模式之工厂模式——简单工厂模式与工厂方法模式比较相关的知识,希望对你有一定的参考价值。
用下面的例子比较:
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面向对象设计模式之工厂模式——简单工厂模式与工厂方法模式比较的主要内容,如果未能解决你的问题,请参考以下文章