利用__new__实现工厂模式

编程

代码如下:

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

"""

以上是 利用__new__实现工厂模式 的全部内容, 来源链接: utcz.com/z/518014.html

回到顶部