利用__new__实现工厂模式

精选30+云产品,助力企业轻松上云!>>> hot3.png

所谓的工厂模式是指通过一个接口,根据参数的取值来创建不同的实例。创建过程的逻辑对外封闭,用户不必关系实现的逻辑。就好比一个工厂可以生产多种零件,用户并不关心生产的过程,只需要告知需要零件的种类。也因此称为工厂模式

代码如下:

class LastOfUs:
	def play(self):
		print("this Last Of Us is really funny")


class Uncharted:
	def play(self):
		print("the Uncharted is really funny")


class PsGame:
	def play(self):
		print("PS has many games")


class GameFactory:
	games = {"last_of_us": LastOfUs, "uncharted": Uncharted}
	
	def __new__(cls, name):
		if name in cls.games:
			return cls.games[name]()
		return PsGame()


uncharted = GameFactory("uncharted")

last_of_us = GameFactory("last_of_us")

uncharted.play()
last_of_us.play()

"""
the Uncharted is really funny
this Last Of Us is really funny

"""

你可能感兴趣的:(设计模式,python,java,linux,大数据)