简明设计模式教程-工厂方法、简单工厂和抽象工厂

工厂方法模式

工厂方法使用函数封装对象的声明,隐藏了创建对象的所有细节。一个类对应一个工厂方法。

class Animal():
	def shout(self):
		print('未知!')

class Cat(Animal):
	def shout(self):
		return '喵'

class Dog(Animal):
	def shout(self):
		return '汪'

def createCat():
	return Cat()

def createDog():
	return Dog()

cat = createCat()
cat.shout()

dog = createDog()
dog.shout()

简单工厂模式

简单工厂封装同一族类的对象声明,通过函数参数指定具体的类。不但大大简化了分别为每个类编写工厂方法的繁琐过程,并且可以实现参数化创建对象,增加了灵活性。

def createPet(type=''):
	if type == 'cat':
		return Cat()
	elif type == 'dog':
		return Dog()
	else:
		return Animal()

for type in ['cat', 'dog']:
	print(f'宠物{type}的叫声是:{createPet(type).shout()}!')

运行结果:
宠物cat的叫声是:喵!
宠物dog的叫声是:汪!

工厂类/抽象工厂

工厂封装一组相关性强不同族系的对象的声明,这组对象共同实现特定的任务。工厂类表示不同的状态、风格、条件、环境等,工厂类底下的工厂方法则表示不同类的对象。工厂类为对象的统一管理、组织和划分提供强大的能力。

class PetFactory():
	def createPet(self):
		return Animal()
	def createFood(self):
		print('食物')

class DogFactory(PetFactory):
	def createPet(self):
		return Dog()
	def createFood(self):
		return '狗粮'

class CatFactory(PetFactory):
	def createPet(self):
		return Cat()
	def createFood(self):
		return '猫粮'

def createPetFactory(type=''):
	if type == 'cat':
		return CatFactory()
	elif type == 'dog':
		return DogFactory()
	else:
		return PetFactory()

pet = 'cat'
factory = createPetFactory(pet)
print(f'宠物{pet}的叫声是:{factory.createPet().shout()}!它喜欢吃{factory.createFood()}。')

运行结果:
宠物cat的叫声是:喵!它喜欢吃猫粮。

本文是简明设计模式教程系列之一,常用的设计模式有23种之多,接下来还有更多更精彩设计模式的介绍,欢迎评论、转发、收藏和关注,点击合集有更多内容。

简明设计模式教程——面向对象编程

发表评论
留言与评论(共有 0 条评论) “”
   
验证码:

相关文章

推荐文章