dimanche 24 septembre 2017

Design Pattern to merge two implementations into one class

I can't figure out the correct way to model this problem. Here I give you a minimalistic version of my code:

# -*- coding: utf-8 -*-
from abc import ABCMeta, abstractmethod

class AreaCalculator():
    __metaclass__ = ABCMeta

    def __init__(self):
        pass

    @abstractmethod
    def getArea(self):
        pass

    def compute(self):
        self.getArea()


class PerimeterCalculator():
    __metaclass__ = ABCMeta

    def __init__(self):
        pass

    @abstractmethod
    def getPerimeter(self):
        pass

    def compute(self):
        self.getPerimeter()


class TriangleAreaCalculator(AreaCalculator):

    def __init__(self):
        AreaCalculator.__init__(self)

    def getArea(self):
        return area

class TrianglePerimeterCalculator(PerimeterCalculator):

    def __init__(self):
        PerimeterCalculator.__init__(self)

    def getPerimeter(self):
        return perimeter



a = TriangleAreaCalculator()
b = TrianglePerimeterCalculator()

Is there an elegant way to merge "TrianglePerimeterCalculator" and "TriangleAreaCalculator" classes into one, but keeping "PerimeterCalculator" and "AreaCalculator" separated?

[edit] As Kyle suggested in the comments, I can create a new class (let's call it "Triangle") that inherits from "PerimeterCalculator" and "AreaCalculator" at the same time, but what I want is to be able to tell a new instance of "Triangle" to behave as "PerimeterCalculator" or "AreaCalculator", but not both at the same time.

Aucun commentaire:

Enregistrer un commentaire