Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Python Examples #113

Open
wants to merge 4 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
49 changes: 49 additions & 0 deletions Python/Behavioral/ChainOfResponsibility.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,49 @@
import inspect

class Account:
_successor = None
_balance = None

def setNext(self, account):
self._successor = account

def pay(self, amountToPay):
import inspect
myCaller = inspect.stack()[1][3]
if self.canPay(amountToPay):
print "Paid " + str(amountToPay) + " using " + myCaller
elif (self._successor):
print "Cannot pay using " + myCaller + ". Proceeding .."
self._successor.pay(amountToPay)
else:
raise ValueError('None of the accounts have enough balance')
def canPay(self, amount):
return self.balance >= amount

class Bank(Account):
_balance = None

def __init__(self, balance):
self.balance = balance

class Paypal(Account):
_balance = None

def __init__(self, balance):
self.balance = balance

class Bitcoin(Account):
_balance = None

def __init__(self, balance):
self.balance = balance

if __name__ == '__main__':
bank = Bank(100)
paypal = Paypal(200)
bitcoin = Bitcoin(300)

bank.setNext(paypal)
paypal.setNext(bitcoin)

bank.pay(259)
60 changes: 60 additions & 0 deletions Python/Behavioral/Command.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,60 @@
class Bulb:
def turnOn(self):
print "Bulb has been lit"

def turnOff(self):
print "Darkness!"

class Command:
def execute(self):
pass

def undo(self):
pass

def redo(self):
pass

class TurnOn(Command):
_bulb = None

def __init__(self, bulb):
self._bulb = bulb

def execute(self):
self._bulb.turnOn()

def undo(self):
self._bulb.turnOff()

def redo(self):
self.execute()

class TurnOff(Command):
_bulb = None

def __init__(self, bulb):
self.bulb = bulb

def execute(self):
self.bulb.turnOff()

def undo(self):
self.bulb.turnOn()

def redo(self):
self.execute()

class RemoteControl:
def submit(self, command):
command.execute()

if __name__ == '__main__':
bulb = Bulb()

turnOn = TurnOn(bulb)
turnOff = TurnOff(bulb)

remote = RemoteControl()
remote.submit(turnOn) # Bulb has been lit!
remote.submit(turnOff) # Darkness!
41 changes: 41 additions & 0 deletions Python/Behavioral/Iterator.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,41 @@
class RadioStation:
_frequency = None

def __init__(self, frequency):
self._frequency = frequency

def getFrequency(self):
return self._frequency

class StationList:
_stations = []
_counter = 0

def addStation(self, station):
self._stations.append(station)

def removeStation(self, toRemove):
toRemoveFrequency = toRemove.getFrequency()
self._stations = filter(lambda station: station.getFrequency() != toRemoveFrequency, self._stations)

def __iter__(self):
return iter(self._stations)

def next(self):
self._counter += 1

if __name__ == '__main__':
stationList = StationList()

stationList.addStation(RadioStation(89))
stationList.addStation(RadioStation(101))
stationList.addStation(RadioStation(102))
stationList.addStation(RadioStation(103))

for station in stationList:
print station.getFrequency()

stationList.removeStation(RadioStation(89))

for station in stationList:
print station.getFrequency()
34 changes: 34 additions & 0 deletions Python/Behavioral/Mediator.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
class ChatRoomMediator:
def showMessage(self, user, message):
pass

class ChatRoom(ChatRoomMediator):
def showMessage(self, user, message):
import datetime
time = datetime.datetime.now()
sender = user.getName()

print str(time) + '[' + sender + ']: ' + message

class User:
_name = None
_chatMediator = None

def __init__(self, name, chatMediator):
self.name = name
self._chatMediator = chatMediator

def getName(self):
return self.name

def send(self, message):
self._chatMediator.showMessage(self, message)

if __name__ == '__main__':
mediator = ChatRoom()

john = User('John Doe', mediator)
jane = User('Jane Doe', mediator)

john.send('Hi There!')
jane.send('Hey!')
36 changes: 36 additions & 0 deletions Python/Behavioral/Memento.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
class EditorMemento:
_content = None

def __init__(self, content):
self.content = content

def getContent(self):
return self.content

class Editor:
_content = ''

def type(self, words):
self._content = self._content + ' ' + words

def getContent(self):
return self._content

def save(self):
return EditorMemento(self._content)

def restore(self, memento):
self.content = memento.getContent()

editor = Editor()
editor.type('This is the first sentence')
editor.type('This is the second.')

#Save the state to restore to : This is the first sentence. This is second.
saved = editor.save()
editor.type('And this is the third')

print editor.getContent() # This is the first sentence. This is second. And this is third.

editor.restore(saved)
editor.getContent() # This is the first sentence. This is second.
45 changes: 45 additions & 0 deletions Python/Behavioral/Observer.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,45 @@
class JobPost:
_title = None

def __init__(self, title):
self.title = title

def getTitle(self):
return self.title

class JobSeeker:
_name = None

def __init__(self, name):
self.name = name

def onJobPosted(self, job):
print 'Hi ' + self.name + '! New job posted: ' + job.getTitle()

class EmploymentAgency:
_observers = []

def notify(self, jobPosting):
for observer in self._observers:
observer.onJobPosted(jobPosting)

def attach(self, observer):
self._observers.append(observer)

def addJob(self, jobPosting):
self.notify(jobPosting)


johnDoe = JobSeeker('John Doe')
janeDoe = JobSeeker('Jane Doe')

jobPostings = EmploymentAgency()
jobPostings.attach(janeDoe)
jobPostings.attach(johnDoe)

jobPostings.addJob(JobPost('Software Engineer'))
'''
Output
Hi John Doe! New job posted: Software Engineer
Hi Jane Doe! New job posted: Software Engineer
'''
39 changes: 39 additions & 0 deletions Python/Behavioral/State.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,39 @@
class WritingState:
def write(self, words):
pass

class UpperCase(WritingState):
def write(self, words):
print words.upper()

class LowerCase(WritingState):
def write(self, words):
print words.lower()

class DefaultText(WritingState):
def write(self, words):
print words

class TextEditor():
_state = None

def __init__(self, state):
self._state = state

def setState(self, state):
self._state = state

def type(self, words):
self._state.write(words)

editor = TextEditor(DefaultText())
editor.type('First Line')
editor.setState(UpperCase())

editor.type('Second Line')
editor.type('Third Line')

editor.setState(LowerCase())

editor.type('Fourth Line')
editor.type('Fifth Line')
31 changes: 31 additions & 0 deletions Python/Behavioral/Strategy.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
class SortStrategy:
def sort(self, dataset):
pass

class BubbleSortStrategy(SortStrategy):
def sort(self, dataset):
print 'Sorting using bubble sort'

return dataset

class QuickSortStrategy(SortStrategy):
def sort(self, dataset):
print 'Sorting using quick sort'
return dataset

class Sorter:
_sorter = None

def __init__(self, sorter):
self._sorter = sorter

def sort(self, dataset):
return self._sorter.sort(dataset)

dataset = [1, 5, 4, 3, 2, 8]

sorter = Sorter(BubbleSortStrategy())
sorter.sort(dataset)

sorter = Sorter(QuickSortStrategy())
sorter.sort(dataset)
Loading