Created
June 7, 2018 10:46
-
-
Save AloyASen/1cd82f387c47750e010b1b149f568892 to your computer and use it in GitHub Desktop.
Example strategy pattern in Python
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import math | |
class Metric(object): | |
"""Abstract class""" | |
def distance(self,x,y): | |
raise NotImplementedError("Derived classes should implement this.") | |
class EuclideanMetric(Metric): | |
"""Calculates distance from origin in R according to Pythagorean distance""" | |
def distance(self,x,y): | |
return math.sqrt(x*x+y*y) | |
class ManhattanMetric(Metric): | |
"""Calculates distance from origin in R according to Manhattan Metric""" | |
def distance(self,x,y): | |
return abs(x)+abs(y) | |
class Consumer(Metric): | |
"""We can use this class to use either of the two metrics""" | |
def __init__(self, arg): | |
self.metric = arg() | |
def distance(self,x,y): | |
return self.metric.distance(x,y) | |
euclid = Consumer(EuclideanMetric) | |
print(euclid.distance(3,4)) | |
manhattan = Consumer(ManhattanMetric) | |
print(manhattan.distance(1,-2)) | |
###### Raises NotImplementedException | |
#error = Metric(object) | |
#print(error.distance(1,2)) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment