简单工厂模式

UML类图:


代码示例:

    //基类
    public abstract class Animal
    {
        public string Name { get; set; }
        public abstract void Run();
    }
    //子类1
    public class Chicken : Animal
    {
        public override void Run()
        {
            Console.WriteLine("Chicken was running...");
        }
    }
    //子类2
    public class Dog : Animal
    {
        public override void Run()
        {
            Console.WriteLine("Dog was running...");
        }
    }
    //工厂类
    public class AnimalFactory
    {
        public Animal CreateAnimal(string animalType)
        {
            switch (animalType) //依靠字符串分类
            {
                case "chicken":
                    return new Chicken();
                case "dog":
                    return new Dog();
                default:
                    throw new Exception("Invalid param...");
            }
        }
    }

 

Python代码:

>>> class Human:
... 	def GetDailyLife(self):
... 		raise NotImplimentedError("Abstract")
... 	
>>> class Man(Human):
... 	def GetDailyLife(self):
... 		return "Sure to game, playing and so on."
... 	
>>> class Woman(Human):
... 	def GetDailyLife(self):
... 		return "Shopping..."
... 	
>>> class HumanFactory:
... 	def GetHumanInstance(self, humanStr):
... 		if(humanStr=="man"):
... 			return Man()
... 		elif(humanStr=="woman"):
... 			return Woman()
... 		else:
... 			return None
... 		
>>> humanInstance=HumanFactory().GetHumanInstance('man')
>>> humanInstance.GetDailyLife()
'Sure to game, playing and so on.'
>>> humanInstance=HumanFactory().GetHumanInstance('woman')
>>> humanInstance.GetDailyLife()
'Shopping...'
>>> 


 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值