Builder Pattern

Jason subPose at gmail.com
Thu Feb 2 07:24:11 EST 2006


I have converted another example of strategy which I prefer to the 2
described earlier, here it is:

class FindMinima:
	def algorithm(self):raise NotImplementedError


class LeastSquares (FindMinima):
	def algorithm(self,line):
		return (1.1,2.2)


class NewtonsMethod (FindMinima):
	def algorithm(self,line):
		return (3.3,4.4)

class Bisection (FindMinima):
	def algorithm(self,line):
		return (5.5,6.6)

class ConjugateGradient (FindMinima):
	def algorithm(self,line):
		return (3.3,4.4)



class MinimaSolver: # context class
	strategy=''
	def __init__ (self,strategy):
		self.strategy=strategy

	def minima(self,line):
		return self.strategy.algorithm(line)

	def changeAlgorithm(self,newAlgorithm):
		self.strategy = newAlgorithm

def test():
	solver=MinimaSolver(LeastSquares())
	print solver.minima((5.5,5.5))
	solver.changeAlgorithm(Bisection())
	print solver.minima((5.5,5.5))
test()




More information about the Python-list mailing list