python在工厂中的应用_Python中的类工厂

I'm new to Python and need some advice implementing the scenario below.

I have two classes for managing domains at two different registrars. Both have the same interface, e.g.

class RegistrarA(Object):

def __init__(self, domain):

self.domain = domain

def lookup(self):

...

def register(self, info):

...

and

class RegistrarB(object):

def __init__(self, domain):

self.domain = domain

def lookup(self):

...

def register(self, info):

...

I would like to create a Domain class that, given a domain name, loads the correct registrar class based on the extension, e.g.

com = Domain('test.com') #load RegistrarA

com.lookup()

biz = Domain('test.biz') #load RegistrarB

biz.lookup()

I know this can be accomplished using a factory function (see below), but is this the best way of doing it or is there a better way using OOP features?

def factory(domain):

if ...:

return RegistrarA(domain)

else:

return RegistrarB(domain)

解决方案

I think using a function is fine.

The more interesting question is how do you determine which registrar to load? One option is to have an abstract base Registrar class which concrete implementations subclass, then iterate over its __subclasses__() calling an is_registrar_for() class method:

class Registrar(object):

def __init__(self, domain):

self.domain = domain

class RegistrarA(Registrar):

@classmethod

def is_registrar_for(cls, domain):

return domain == 'foo.com'

class RegistrarB(Registrar):

@classmethod

def is_registrar_for(cls, domain):

return domain == 'bar.com'

def Domain(domain):

for cls in Registrar.__subclasses__():

if cls.is_registrar_for(domain):

return cls(domain)

raise ValueError

print Domain('foo.com')

print Domain('bar.com')

This will let you transparently add new Registrars and delegate the decision of which domains each supports, to them.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值