Skip to content

Instantly share code, notes, and snippets.

@AloyASen
Created June 7, 2018 10:46
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save AloyASen/1cd82f387c47750e010b1b149f568892 to your computer and use it in GitHub Desktop.
Save AloyASen/1cd82f387c47750e010b1b149f568892 to your computer and use it in GitHub Desktop.
Example strategy pattern in Python
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