2017-02-20 48 views
-1

я имел проблемы с получением моей головы вокруг реализации для следующих требований:Определение интерфейса и использование нескольких implemenations интерфейса

  1. Созданием один интерфейс класса Interface.
  2. Создание n классов ImplementationN, которые реализуют Interface по-разному.
  3. Создание одного нового класса UsingInterface, который использует функции от Interface для определения его собственных функций.
  4. Создание n новых классов, которые позволяют использовать функции, созданные в UsingInterface, но реализующие функции, используемые методами UsingInteface одним из классов ImplementationN.

Ниже решение, которое я придумал:

+1

Что вам не нравится? Это [шаблон стратегии] (https://en.wikipedia.org/wiki/Strategy_pattern). –

+0

Я не был уверен, как реализовать это поведение в Python, но думаю, что мне удалось сделать это правильно в приведенном ниже примере. Обратная связь приветствуется. – user1211030

+1

Возможно, сообщение на [codereview.se]. –

ответ

1

Explaination в режиме реального времени. Одним из ключей решения было установить UsingInterface как metaclass=ABCMeta, чтобы он (в данном случае IDE) не нуждался в реализации func1.

from abc import ABCMeta, abstractmethod 


class Interface(object, metaclass=ABCMeta): 
    """Class that defines an interface.""" 
    @abstractmethod 
    def func1(self): 
     pass 


class Implementation1(Interface): 
    """Class that implements the interface one way.""" 
    def func1(self): 
     print('func1 was implemented here') 


class Implementation2(Interface): 
    """Class that implements the interface another way, differently.""" 
    def func1(self): 
     print('func1 was implemented here as well, but differently') 


class UsingInterface(Interface, metaclass=ABCMeta): 
    """Class that uses the interface to implement its own functions. 
    `func1` is not implemented here, hence this has to be an `ABCMeta` class. 
    Later, the correct implementation of `func1` based on the inherited 
    Implementation class shall be used. 

    We're inheriting `Interface`, so the IDE can tell us which methods 
    we can call (in this case `self.func1()`). 
    """ 
    def func2(self): 
     print("I'm running func1 from the Interface: ") 
     self.func1() 


class Usage1(UsingInterface, Implementation1): 
    pass  


class Usage2(UsingInterface, Implementation2): 
    pass 

u1 = Usage1() 
u1.func2() 
# I'm running func1 from the Interface: 
# func1 was implemented here 

u2 = Usage2() 
u2.func2() 
# I'm running func1 from the Interface: 
# func1 was implemented here as well, but differently