2012-05-21 3 views
2

내 코드에 약간의 일반성을 부여하려고한다. 기본적으로 내가 찾고있는 것은 이것입니다.내가 원하는 디자인 패턴은 무엇이며 어떻게 이것을 파이썬으로 구현할 것인가?

class MyAPI(object): 
    def __init__(self): 
     pass 

    def upload(self): 
     pass 

    def download(self): 
     pass 

class MyAPIEx(object): 
    def upload(self): 
     #specific implementation 

class MyAPIEx2(object): 
    def upload(self) 
    #specific implementation 

#Actual usage ... 
def use_api(): 
    obj = MyAPI() 
    obj.upload() 

그래서 내가 원하는 것은 그 구성에 따라 내가 업로드 기능 MyAPIEx 또는 MyAPIEx2 중 하나의
를 호출 할 수있을 것입니다 :

가 나는 API 인터페이스 MyAPI을 작성하고 싶습니다. 내가 찾고있는 정확한 디자인 패턴은 무엇이며 파이썬으로 구현하는 방법은 무엇입니까?

답변

1

정말 당신이 어떤 패턴을 사용하고 있는지, 더 많은 정보없이 말하기가 어렵습니다. MyAPI를 인스턴스화하는 방법은 사실 @Darhazer와 같은 팩토리입니다. 그러나 MyAPI 클래스 계층 구조에 사용되는 패턴에 대해 알고 싶어하고 더 이상의 정보는 말할 필요가 없습니다.

아래에서 몇 가지 코드를 개선 했으므로 개선을 위해 단어를 찾아보십시오.

class MyAPI(object): 
    def __init__(self): 
     pass 

    def upload(self): 
     # IMPROVEMENT making this function abstract 
     # This is how I do it, but you can find other ways searching on google 
     raise NotImplementedError, "upload function not implemented" 

    def download(self): 
     # IMPROVEMENT making this function abstract 
     # This is how I do it, but you can find other ways searching on google 
     raise NotImplementedError, "download function not implemented" 

# IMPROVEMENT Notice that I changed object to MyAPI to inherit from it 
class MyAPIEx(MyAPI): 
    def upload(self): 
     #specific implementation 

# IMPROVEMENT Notice that I changed object to MyAPI to inherit from it 
class MyAPIEx2(MyAPI): 
    def upload(self) 
     #specific implementation 


# IMPROVEMENT changed use_api() to get_api(), which is a factory, 
# call it to get the MyAPI implementation 
def get_api(configDict): 
    if 'MyAPIEx' in configDict: 
     return MyAPIEx() 
    elif 'MyAPIEx2' in configDict: 
     return MyAPIEx2() 
    else 
     # some sort of an error 

# Actual usage ... 
# IMPROVEMENT, create a config dictionary to be used in the factory 
configDict = dict() 
# fill in the config accordingly 
obj = get_api(configDict) 
obj.upload() 
2

Factory method (또는 공장의 다른 구현물)을 찾고 있습니다.

관련 문제