├── .gitignore
├── pydesignpatterns
├── diagrams
│ ├── builder.png
│ ├── prototype.png
│ ├── singleton.png
│ ├── abstractfactory.png
│ ├── factorymethod.png
│ ├── simplefactory.png
│ └── chainofresponsibility.png
├── results
│ ├── singleton.png
│ ├── builder_naive.PNG
│ ├── builder_aircraft.png
│ ├── prototype_naive.png
│ ├── prototype_shape.png
│ ├── singleton_lazy.png
│ ├── singleton_thread.png
│ ├── factorymethod_car.png
│ ├── singleton_counter.png
│ ├── abstractfactory_naive.png
│ ├── abstractfactory_shape.png
│ ├── factorymethod_naive.png
│ ├── simplefactory_burger.png
│ ├── simplefactory_naive.png
│ ├── simplefactory_pizza.png
│ ├── singleton_decorated.png
│ ├── singleton_metaclass.png
│ └── factorymethod_cellphone.png
├── utility.py
├── creational
│ ├── singleton_naive.py
│ ├── singleton_counter.py
│ ├── singleton_lazy_instantiation.py
│ ├── singleton_thread.py
│ ├── builder_naive.py
│ ├── singleton_metaclass.py
│ ├── singleton_decorator.py
│ ├── prototype_naive.py
│ ├── prototype_shape.py
│ ├── simplefactory_naive.py
│ ├── factorymethod_naive.py
│ ├── abstractfactory_naive.py
│ ├── builder_aircraft.py
│ ├── abstractfactory_shape.py
│ ├── simplefactory_burger.py
│ ├── factorymethod_cellphone.py
│ ├── simplefactory_pizza.py
│ └── factorymethod_car.py
└── behavioral
│ └── chain_of_responsibility_planet.py
├── tests
├── test_prototype.py
├── test_builder.py
├── test_singleton.py
└── test_factory.py
├── README.md
└── LICENSE
/.gitignore:
--------------------------------------------------------------------------------
1 | tests/__pycache__
2 | pydesignpatterns/__pycache__
3 | pydesignpatterns/creational/__pycache__
--------------------------------------------------------------------------------
/pydesignpatterns/diagrams/builder.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/avidLearnerInProgress/design-patterns/HEAD/pydesignpatterns/diagrams/builder.png
--------------------------------------------------------------------------------
/pydesignpatterns/diagrams/prototype.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/avidLearnerInProgress/design-patterns/HEAD/pydesignpatterns/diagrams/prototype.png
--------------------------------------------------------------------------------
/pydesignpatterns/diagrams/singleton.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/avidLearnerInProgress/design-patterns/HEAD/pydesignpatterns/diagrams/singleton.png
--------------------------------------------------------------------------------
/pydesignpatterns/results/singleton.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/avidLearnerInProgress/design-patterns/HEAD/pydesignpatterns/results/singleton.png
--------------------------------------------------------------------------------
/pydesignpatterns/results/builder_naive.PNG:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/avidLearnerInProgress/design-patterns/HEAD/pydesignpatterns/results/builder_naive.PNG
--------------------------------------------------------------------------------
/pydesignpatterns/diagrams/abstractfactory.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/avidLearnerInProgress/design-patterns/HEAD/pydesignpatterns/diagrams/abstractfactory.png
--------------------------------------------------------------------------------
/pydesignpatterns/diagrams/factorymethod.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/avidLearnerInProgress/design-patterns/HEAD/pydesignpatterns/diagrams/factorymethod.png
--------------------------------------------------------------------------------
/pydesignpatterns/diagrams/simplefactory.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/avidLearnerInProgress/design-patterns/HEAD/pydesignpatterns/diagrams/simplefactory.png
--------------------------------------------------------------------------------
/pydesignpatterns/results/builder_aircraft.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/avidLearnerInProgress/design-patterns/HEAD/pydesignpatterns/results/builder_aircraft.png
--------------------------------------------------------------------------------
/pydesignpatterns/results/prototype_naive.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/avidLearnerInProgress/design-patterns/HEAD/pydesignpatterns/results/prototype_naive.png
--------------------------------------------------------------------------------
/pydesignpatterns/results/prototype_shape.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/avidLearnerInProgress/design-patterns/HEAD/pydesignpatterns/results/prototype_shape.png
--------------------------------------------------------------------------------
/pydesignpatterns/results/singleton_lazy.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/avidLearnerInProgress/design-patterns/HEAD/pydesignpatterns/results/singleton_lazy.png
--------------------------------------------------------------------------------
/pydesignpatterns/results/singleton_thread.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/avidLearnerInProgress/design-patterns/HEAD/pydesignpatterns/results/singleton_thread.png
--------------------------------------------------------------------------------
/pydesignpatterns/results/factorymethod_car.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/avidLearnerInProgress/design-patterns/HEAD/pydesignpatterns/results/factorymethod_car.png
--------------------------------------------------------------------------------
/pydesignpatterns/results/singleton_counter.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/avidLearnerInProgress/design-patterns/HEAD/pydesignpatterns/results/singleton_counter.png
--------------------------------------------------------------------------------
/pydesignpatterns/results/abstractfactory_naive.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/avidLearnerInProgress/design-patterns/HEAD/pydesignpatterns/results/abstractfactory_naive.png
--------------------------------------------------------------------------------
/pydesignpatterns/results/abstractfactory_shape.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/avidLearnerInProgress/design-patterns/HEAD/pydesignpatterns/results/abstractfactory_shape.png
--------------------------------------------------------------------------------
/pydesignpatterns/results/factorymethod_naive.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/avidLearnerInProgress/design-patterns/HEAD/pydesignpatterns/results/factorymethod_naive.png
--------------------------------------------------------------------------------
/pydesignpatterns/results/simplefactory_burger.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/avidLearnerInProgress/design-patterns/HEAD/pydesignpatterns/results/simplefactory_burger.png
--------------------------------------------------------------------------------
/pydesignpatterns/results/simplefactory_naive.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/avidLearnerInProgress/design-patterns/HEAD/pydesignpatterns/results/simplefactory_naive.png
--------------------------------------------------------------------------------
/pydesignpatterns/results/simplefactory_pizza.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/avidLearnerInProgress/design-patterns/HEAD/pydesignpatterns/results/simplefactory_pizza.png
--------------------------------------------------------------------------------
/pydesignpatterns/results/singleton_decorated.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/avidLearnerInProgress/design-patterns/HEAD/pydesignpatterns/results/singleton_decorated.png
--------------------------------------------------------------------------------
/pydesignpatterns/results/singleton_metaclass.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/avidLearnerInProgress/design-patterns/HEAD/pydesignpatterns/results/singleton_metaclass.png
--------------------------------------------------------------------------------
/pydesignpatterns/diagrams/chainofresponsibility.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/avidLearnerInProgress/design-patterns/HEAD/pydesignpatterns/diagrams/chainofresponsibility.png
--------------------------------------------------------------------------------
/pydesignpatterns/results/factorymethod_cellphone.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/avidLearnerInProgress/design-patterns/HEAD/pydesignpatterns/results/factorymethod_cellphone.png
--------------------------------------------------------------------------------
/pydesignpatterns/utility.py:
--------------------------------------------------------------------------------
1 | """
2 | Author: CHIRAG SHAH
3 | Created On: 7th July 2018
4 | Modified On: 14th July 2018
5 | """
6 |
7 | from pathlib import Path
8 | import matplotlib.pyplot as plt
9 | import matplotlib.image as mimg
10 |
11 | def get_path():
12 | """
13 | Helper utility to get the base paths
14 | """
15 |
16 | P = str(Path().resolve().parent)
17 | CLASS_DIAGRAM_PATH = P + "\\diagrams\\"
18 | CODE_RESULT_PATH = P + "\\results\\"
19 | return CLASS_DIAGRAM_PATH, CODE_RESULT_PATH
20 |
21 | def class_diagram(name):
22 | """
23 | Get class diagram for specific class pattern
24 |
25 | @params: name of class diagram
26 | """
27 |
28 | NAME = name
29 | BASE_PATH, _ = get_path()
30 | PATH = BASE_PATH + NAME
31 |
32 | diagram = mimg.imread(PATH)
33 | plt.axis('off')
34 | plt.subplots_adjust(top = 1, bottom = 0, right = 1, left = 0, hspace = 0, wspace = 0)
35 | plt.suptitle(NAME.split('.')[0], fontsize = 18)
36 | result = plt.imshow(diagram)
37 | return result
38 |
39 | def output_image(name):
40 | """
41 | Get output image for specific class pattern
42 |
43 | @params: name of output image
44 | """
45 |
46 | NAME = name
47 | _, BASE_PATH = get_path()
48 | PATH = BASE_PATH + NAME
49 |
50 | diagram = mimg.imread(PATH)
51 | plt.axis('off')
52 | plt.subplots_adjust(top = 1, bottom = 0, right = 1, left = 0, hspace = 0, wspace = 0)
53 | plt.suptitle(NAME.split('.')[0], fontsize = 18)
54 | result = plt.imshow(diagram)
55 | return result
--------------------------------------------------------------------------------
/pydesignpatterns/creational/singleton_naive.py:
--------------------------------------------------------------------------------
1 | """
2 | Author: CHIRAG SHAH
3 | Created On: 7th July 2018
4 | """
5 |
6 | import inspect, sys
7 | import matplotlib.pyplot as plt
8 | from pathlib import Path
9 |
10 | sys.path.append(str(Path(__file__).resolve().parent.parent))
11 | from utility import class_diagram, output_image
12 |
13 | class Singleton(object):
14 | """
15 | Singleton Class is a naive implementation of Singleton pattern by overriding __new__ method
16 | __new__: First step of instance creation. It's called first, and is responsible for returning a new instance of your class
17 |
18 | @return-values: instance of class, hash value generated for class
19 | """
20 |
21 | __instance = None
22 | __hsh = None
23 | def __new__(cls, *args, **kwargs):
24 | if not cls.__instance:
25 | cls.__instance = object.__new__(cls, *args, **kwargs)
26 | cls.__hsh = cls.__instance.__hash__()
27 | return cls.__instance, cls.__hsh
28 |
29 |
30 | def get_instance():
31 | """
32 | Check if single instance is created for same class by using multiple objects
33 | """
34 |
35 | s1, hsh1 = Singleton()
36 | s2, hsh2 = Singleton()
37 |
38 | print("Hash of instance 1: "+ str(hsh1))
39 | print("Hash of instance 2: "+ str(hsh2))
40 |
41 | if id(s1) == id(s2):
42 | print("Singleton Success")
43 | else:
44 | print("Error")
45 |
46 | def get_code():
47 | """
48 | @return-values: source code
49 | """
50 |
51 | a = inspect.getsource(Singleton)
52 | b = inspect.getsource(get_instance)
53 | return a + '\n' + b
54 |
55 | def get_classdiagram():
56 | """
57 | @return-values: matplotlib object with class diagram
58 | """
59 |
60 | diagram = class_diagram("singleton.png")
61 | #plt.show()
62 | return diagram
63 |
64 | def get_outputimage():
65 | """
66 | @return-values: matplotlib object with code output
67 | """
68 |
69 | output = output_image("singleton.png")
70 | #plt.show()
71 | return output
--------------------------------------------------------------------------------
/pydesignpatterns/creational/singleton_counter.py:
--------------------------------------------------------------------------------
1 | """
2 | Author: CHIRAG SHAH
3 | Created On: 16th July 2018
4 | """
5 |
6 | import inspect, sys
7 | import matplotlib.pyplot as plt
8 | from pathlib import Path
9 |
10 | sys.path.append(str(Path(__file__).resolve().parent.parent))
11 | from utility import class_diagram, output_image
12 |
13 | class SingletonCounter(object):
14 | """
15 | SingletonCounter Class is basic example of how to use Singleton pattern in counting objects
16 | __init__: doesn't return anything; it's only responsible for initializing the instance after it's been created
17 |
18 | @return-values: count value, instance of class
19 | """
20 |
21 | __instance = None
22 | __cnt = 0
23 |
24 | def __init__(self):
25 | pass
26 |
27 | def get_count(self):
28 | self.__cnt += 1
29 | return self.__cnt
30 |
31 | def get_instance():
32 | if SingletonCounter.__instance == None:
33 | SingletonCounter.__instance = SingletonCounter()
34 | else:
35 | pass
36 | return SingletonCounter.__instance
37 |
38 | def test_instance():
39 | """
40 | Check for count++
41 | """
42 |
43 | print("Instance id | Count")
44 |
45 | s1 = SingletonCounter.get_instance()
46 | print(str(id(s1)) + " : " + str(s1.get_count()))
47 |
48 | s2 = SingletonCounter.get_instance()
49 | print(str(id(s2)) + " : " + str(s2.get_count()))
50 |
51 | s3 = SingletonCounter.get_instance()
52 | print(str(id(s2)) + " : " + str(s3.get_count()))
53 |
54 |
55 | def get_code():
56 | """
57 | @return-values: source code
58 | """
59 |
60 | a = inspect.getsource(SingletonCounter)
61 | b = inspect.getsource(test_instance)
62 | return a + '\n' + b
63 |
64 | def get_classdiagram():
65 | """
66 | @return-values: matplotlib object with class diagram
67 | """
68 |
69 | diagram = class_diagram("singleton.png")
70 | #plt.show()
71 | return diagram
72 |
73 | def get_outputimage():
74 | """
75 | @return-values: matplotlib object with code output
76 | """
77 |
78 | output = output_image("singleton_counter.png")
79 | #plt.show()
80 | return output
--------------------------------------------------------------------------------
/tests/test_prototype.py:
--------------------------------------------------------------------------------
1 | """
2 | Author: CHIRAG SHAH
3 | Created On: 16th October 2018
4 | Modified On: 16th October 2018
5 | """
6 |
7 | import unittest, sys, inspect
8 | from pathlib import Path
9 | from abc import ABCMeta
10 |
11 |
12 | ROOT_DIR = str(Path(__file__).resolve().parent.parent)
13 | sys.path.append(ROOT_DIR)
14 |
15 | from pydesignpatterns.creational import (
16 | builder_aircraft,
17 | builder_naive
18 | )
19 |
20 | class TestBuilder(unittest.TestCase):
21 |
22 | def test_classes(self):
23 | self.assertEqual(inspect.isclass(builder_naive.Director), True)
24 | self.assertEqual(inspect.isclass(builder_naive.Product), True)
25 | self.assertEqual(inspect.isclass(builder_naive.Builder), True)
26 | self.assertEqual(inspect.isclass(builder_naive.ConcreteBuilder), True)
27 |
28 | def test_instances(self):
29 | self.assertEqual(isinstance(builder_naive.ConcreteBuilder(), builder_naive.Builder), True)
30 | self.assertEqual(isinstance(builder_naive.Builder, ABCMeta), True)
31 |
32 | def test_builder(self):
33 | concrete_builder = builder_naive.ConcreteBuilder()
34 | director = builder_naive.Director()
35 | director.construct(concrete_builder)
36 | product = concrete_builder.product
37 |
38 | class TestBuilderAircraft(unittest.TestCase):
39 |
40 | def test_classes(self):
41 | self.assertEqual(inspect.isclass(builder_aircraft.Aircraft), True)
42 | self.assertEqual(inspect.isclass(builder_aircraft.AircraftBuilder), True)
43 | self.assertEqual(inspect.isclass(builder_aircraft.Airbus380Builder), True)
44 | self.assertEqual(inspect.isclass(builder_aircraft.Cessna172Builder), True)
45 | self.assertEqual(inspect.isclass(builder_aircraft.AircraftDirector), True)
46 |
47 | def test_instances(self):
48 | self.assertEqual(isinstance(builder_aircraft.AircraftBuilder, ABCMeta), True)
49 | self.assertEqual(isinstance(builder_aircraft.Airbus380Builder(), builder_aircraft.AircraftBuilder), True)
50 | self.assertEqual(isinstance(builder_aircraft.Cessna172Builder(), builder_aircraft.AircraftBuilder), True)
51 |
52 | def test_builderaircraft(self):
53 | aircraft_builder = builder_aircraft.Airbus380Builder()
54 | aircraft_builder.create_aircraft()
55 | aircraft_director = builder_aircraft.AircraftDirector()
56 | aircraft = aircraft_director.build(aircraft_builder)
57 | x = builder_aircraft.get_custom_fields_str(aircraft)
58 | self.assertEqual(len(x), 105)
--------------------------------------------------------------------------------
/pydesignpatterns/creational/singleton_lazy_instantiation.py:
--------------------------------------------------------------------------------
1 | """
2 | Author: CHIRAG SHAH
3 | Created On: 8th July 2018
4 | """
5 |
6 | import inspect, sys
7 | import matplotlib.pyplot as plt
8 | from pathlib import Path
9 |
10 | sys.path.append(str(Path(__file__).resolve().parent.parent))
11 | from utility import class_diagram, output_image
12 |
13 | class SingletonLazy(object):
14 | """
15 | SingletonLazy Class is naive implementation of Singleton Pattern with help of lazy instantiation
16 | Lazy instantiation: Object gets created only when its needed
17 | __init__: doesn't return anything; it's only responsible for initializing the instance after it's been created
18 |
19 | @return-values: instance of class
20 | """
21 |
22 | __instance = None
23 |
24 | def __init__(self):
25 | if not SingletonLazy.__instance:
26 | print("Instance doesn't exist, hence creating it via __init__()")
27 | else:
28 | print("Instance already exists:", self.get_instance())
29 |
30 | @classmethod
31 | def get_instance(cls):
32 | if not cls.__instance:
33 | cls.__instance = SingletonLazy()
34 | return cls.__instance
35 |
36 | def test_lazy():
37 | """
38 | Showcases how lazy instantiation works in Singleton Pattern
39 | """
40 |
41 | s1 = SingletonLazy() #Here only class is initialised, but object of class isn't created
42 | print(type(s1))
43 |
44 | print("Object created.", SingletonLazy.get_instance()) #Object is created here
45 |
46 | s2 = SingletonLazy().get_instance() #Object already exists
47 | s3 = SingletonLazy().get_instance() #Object already exists
48 | s4 = SingletonLazy().get_instance() #Object already exists
49 |
50 | if id(s3) == id(s4):
51 | print("SingletonLazy Success")
52 | else:
53 | print("Error")
54 |
55 | print("Recheck:")
56 | recheck = s2 is s3 is s4
57 | print("s2 == s3 == s4: " +str(recheck))
58 |
59 | def get_code():
60 | """
61 | @return-values: source code
62 | """
63 |
64 | a = inspect.getsource(SingletonLazy)
65 | b = inspect.getsource(test_lazy)
66 | return a + '\n' + b
67 |
68 | def get_classdiagram():
69 | """
70 | @return-values: matplotlib object with class diagram
71 | """
72 |
73 | diagram = class_diagram("singleton.png")
74 | #plt.show()
75 | return diagram
76 |
77 | def get_outputimage():
78 | """
79 | @return-values: matplotlib object with code output
80 | """
81 |
82 | output = output_image("singleton_lazy.png")
83 | #plt.show()
84 | return output
--------------------------------------------------------------------------------
/tests/test_builder.py:
--------------------------------------------------------------------------------
1 | """
2 | Author: CHIRAG SHAH
3 | Created On: 10th October 2018
4 | Modified On: 14th October 2018
5 | """
6 |
7 | import unittest, sys, inspect
8 | from pathlib import Path
9 | from abc import ABCMeta
10 |
11 |
12 | ROOT_DIR = str(Path(__file__).resolve().parent.parent)
13 | sys.path.append(ROOT_DIR)
14 |
15 | from pydesignpatterns.creational import (
16 | builder_aircraft,
17 | builder_naive
18 | )
19 |
20 | class TestBuilder(unittest.TestCase):
21 |
22 | def test_classes(self):
23 | self.assertEqual(inspect.isclass(builder_naive.Director), True)
24 | self.assertEqual(inspect.isclass(builder_naive.Product), True)
25 | self.assertEqual(inspect.isclass(builder_naive.Builder), True)
26 | self.assertEqual(inspect.isclass(builder_naive.ConcreteBuilder), True)
27 |
28 | def test_instances(self):
29 | self.assertEqual(isinstance(builder_naive.ConcreteBuilder(), builder_naive.Builder), True)
30 | self.assertEqual(isinstance(builder_naive.Builder, ABCMeta), True)
31 |
32 | def test_builder(self):
33 | concrete_builder = builder_naive.ConcreteBuilder()
34 | director = builder_naive.Director()
35 | director.construct(concrete_builder)
36 | product = concrete_builder.product
37 | #Unable to identify any assertion condition for product. Let me know if anyone finds :)
38 |
39 | class TestBuilderAircraft(unittest.TestCase):
40 |
41 | def test_classes(self):
42 | self.assertEqual(inspect.isclass(builder_aircraft.Aircraft), True)
43 | self.assertEqual(inspect.isclass(builder_aircraft.AircraftBuilder), True)
44 | self.assertEqual(inspect.isclass(builder_aircraft.Airbus380Builder), True)
45 | self.assertEqual(inspect.isclass(builder_aircraft.Cessna172Builder), True)
46 | self.assertEqual(inspect.isclass(builder_aircraft.AircraftDirector), True)
47 |
48 | def test_instances(self):
49 | self.assertEqual(isinstance(builder_aircraft.AircraftBuilder, ABCMeta), True)
50 | self.assertEqual(isinstance(builder_aircraft.Airbus380Builder(), builder_aircraft.AircraftBuilder), True)
51 | self.assertEqual(isinstance(builder_aircraft.Cessna172Builder(), builder_aircraft.AircraftBuilder), True)
52 |
53 | def test_builderaircraft(self):
54 | aircraft_builder = builder_aircraft.Airbus380Builder()
55 | aircraft_builder.create_aircraft()
56 | aircraft_director = builder_aircraft.AircraftDirector()
57 | aircraft = aircraft_director.build(aircraft_builder)
58 | x = builder_aircraft.get_custom_fields_str(aircraft)
59 | self.assertEqual(len(x), 105)
--------------------------------------------------------------------------------
/pydesignpatterns/creational/singleton_thread.py:
--------------------------------------------------------------------------------
1 | """
2 | Author: CHIRAG SHAH
3 | Created On: 11th July 2018
4 | """
5 |
6 | import inspect, sys
7 | import matplotlib.pyplot as plt
8 | import _thread as thread
9 | from pathlib import Path
10 |
11 | sys.path.append(str(Path(__file__).resolve().parent.parent))
12 | from utility import class_diagram, output_image
13 |
14 | class SingletonThread(object):
15 | """
16 | SingletonThread is thread-safe implementation of Singleton Pattern
17 | __new__: First step of instance creation. It's called first, and is responsible for returning a new instance of your class
18 | __init__: doesn't return anything; it's only responsible for initializing the instance after it's been created
19 |
20 | @return-values: instance of class, thread-id operating on class
21 | """
22 |
23 | __lockObj = thread.allocate_lock() #lock object
24 | __instance = None
25 |
26 | def __new__(cls, *args, **kargs):
27 | return cls.get_instance(cls)
28 |
29 | def __init__(self):
30 | pass
31 |
32 | def gettid(self):
33 | #Printing thread identifier shows that only one thread operates at a given point of time within the class
34 |
35 | tid = str(thread.get_ident())
36 | return tid
37 |
38 | @classmethod
39 | def get_instance(cls, *args, **kargs):
40 | """
41 | Static method to have a reference to unique instance
42 | """
43 |
44 | #Critical section start
45 | cls.__lockObj.acquire()
46 | try:
47 | if cls.__instance is None:
48 | cls.__instance = object.__new__(cls)
49 |
50 | finally:
51 | cls.__lockObj.release()
52 | #critical section end
53 |
54 | return cls.__instance
55 |
56 | def test_thread():
57 | """
58 | Shows how thread-safe singleton works
59 | """
60 |
61 | s2 = SingletonThread().get_instance()
62 | t2 = int(s2.gettid())
63 |
64 | s3 = SingletonThread().get_instance()
65 | t3 = int(s3.gettid())
66 |
67 | s4 = SingletonThread().get_instance()
68 | t4 = int(s4.gettid())
69 |
70 | print(s2 is s3 is s4)
71 | print("tid:" + str(t2))
72 | if t2 == t3 == t4:
73 | print(True)
74 |
75 | def get_code():
76 | """
77 | @return-values: source code
78 | """
79 |
80 | a = inspect.getsource(SingletonThread)
81 | b = inspect.getsource(test_thread)
82 | return a + '\n' + b
83 |
84 |
85 | def get_classdiagram():
86 | """
87 | @return-values: matplotlib object with class diagram
88 | """
89 |
90 | diagram = class_diagram("singleton.png")
91 | #plt.show()
92 | return diagram
93 |
94 | def get_outputimage():
95 | """
96 | @return-values: matplotlib object with code output
97 | """
98 |
99 | output = output_image("singleton_thread.png")
100 | #plt.show()
101 | return output
--------------------------------------------------------------------------------
/pydesignpatterns/creational/builder_naive.py:
--------------------------------------------------------------------------------
1 | """
2 | Author: CHIRAG SHAH
3 | Created On: 18th September 2018
4 | Modified On: 14th October 2018
5 | """
6 |
7 | import inspect, sys
8 | import matplotlib.pyplot as plt
9 | from pathlib import Path
10 | from abc import ABCMeta, abstractmethod
11 |
12 | sys.path.append(str(Path(__file__).resolve().parent.parent))
13 | from utility import class_diagram, output_image
14 |
15 | class Director:
16 | """
17 | This class constructs an object using the Builder Interface
18 | """
19 |
20 | def __init__(self):
21 | self.build = None
22 |
23 | def construct(self, builder):
24 | self.build = builder
25 | self.build.build_a()
26 | self.build.build_b()
27 | self.build.build_c()
28 |
29 | class Builder(metaclass = ABCMeta):
30 | """
31 | This class specifies abstract interface for creating parts of builder object
32 | """
33 |
34 | def __init__(self):
35 | self.product = Product()
36 |
37 |
38 | @abstractmethod
39 | def build_a(self):
40 | pass
41 |
42 | @abstractmethod
43 | def build_b(self):
44 | pass
45 |
46 | @abstractmethod
47 | def build_c(self):
48 | pass
49 |
50 |
51 | class ConcreteBuilder(Builder):
52 | """
53 | Construct and assemble parts of the product by implementing the Builder interface.
54 | Define and keep track of the representation it creates.
55 | Provide an interface for retrieving the product.
56 | """
57 |
58 | def build_a(self):
59 | print('Building A..')
60 |
61 | def build_b(self):
62 | print('Building B..')
63 |
64 | def build_c(self):
65 | print('Building C..')
66 |
67 | class Product:
68 | """
69 | Represent object under construction
70 | """
71 |
72 | pass
73 |
74 |
75 | def test_builder():
76 | """
77 | Demonstration of builder pattern
78 | """
79 |
80 | concrete_builder = ConcreteBuilder()
81 | director = Director()
82 | director.construct(concrete_builder)
83 | product = concrete_builder.product
84 |
85 | def get_code():
86 | """
87 | @return-values: source code
88 | """
89 | a = inspect.getsource(Director)
90 | b = inspect.getsource(Builder)
91 | c = inspect.getsource(ConcreteBuilder)
92 | d = inspect.getsource(Product)
93 | e = inspect.getsource(test_builder)
94 |
95 | return a + '\n' + b + '\n' + c + '\n' + d + '\n' + e
96 |
97 | def get_classdiagram():
98 | """
99 | @return-values: matplotlib object with class diagram
100 | """
101 |
102 | diagram = class_diagram("builder.png")
103 | plt.show()
104 | return diagram
105 |
106 | def get_outputimage():
107 | """
108 | @return-values: matplotlib object with code output
109 | """
110 |
111 | output = output_image("builder_naive.png")
112 | plt.show()
113 | return output
114 |
115 | test_builder()
--------------------------------------------------------------------------------
/pydesignpatterns/creational/singleton_metaclass.py:
--------------------------------------------------------------------------------
1 | """
2 | Author: CHIRAG SHAH
3 | Created On: 14th July 2018
4 | """
5 |
6 | import inspect, sys
7 | import matplotlib.pyplot as plt
8 | from pathlib import Path
9 |
10 | sys.path.append(str(Path(__file__).resolve().parent.parent))
11 | from utility import class_diagram, output_image
12 |
13 | class SingletonMetaclass(type):
14 | """
15 | SingletonMetaclass is a naive implementation of Singleton pattern by using metaclasses
16 | __call__: this method is called when the instance is called, it allows to return arbitary values
17 | __init__: doesn't return anything; it's only responsible for initializing the instance after it's been created
18 |
19 | @return-values: instance of class
20 | """
21 |
22 | __instance = None
23 |
24 | def __init__(cls, name, bases, namespace):
25 | super().__init__(name, bases, namespace)
26 | cls.__instance = None
27 |
28 | def __call__(cls, *args, **kwargs):
29 | if cls.__instance is None:
30 | cls.__instance = super().__call__(*args, **kwargs)
31 | return cls.__instance
32 |
33 | class TestMeta(metaclass = SingletonMetaclass):
34 | """
35 | TestMeta uses SingletonMetaclass as its metaclass
36 | : metaclass is class of class
37 | : Python - everything is an object
38 | : `type` is a special keyword which holds the authority to create classes(which are objects in itself)
39 | : so we have - object is instance of class and class is instance of `type`
40 | : Every subclass of this class initialises its instance field to None
41 |
42 | @params: class to be used as metaclass
43 | """
44 |
45 | pass
46 |
47 | class A(TestMeta):
48 | """
49 | @params: class(metaclass) to inherit
50 | """
51 |
52 | pass
53 |
54 | class B(A):
55 | """
56 | @params: class to inherit
57 | """
58 |
59 | pass
60 |
61 |
62 | def get_instance():
63 | """
64 | Test for instances of metaclass
65 | """
66 |
67 | print(A())
68 | print(B())
69 |
70 | if isinstance(A, SingletonMetaclass) == isinstance(B, SingletonMetaclass):
71 | print("Metaclass Success")
72 | else:
73 | print("Error")
74 |
75 |
76 | def get_code():
77 | """
78 | @return-values: source code
79 | """
80 |
81 | a = inspect.getsource(SingletonMetaclass)
82 | b = inspect.getsource(TestMeta)
83 | c = inspect.getsource(A)
84 | d = inspect.getsource(B)
85 | e = inspect.getsource(get_instance)
86 | return a + '\n' + b + '\n' + c + '\n' + d + '\n' + e
87 |
88 | def get_classdiagram():
89 | """
90 | @return-values: matplotlib object with class diagram
91 | """
92 |
93 | diagram = class_diagram("singleton.png")
94 | #plt.show()
95 | return diagram
96 |
97 | def get_outputimage():
98 | """
99 | @return-values: matplotlib object with code output
100 | """
101 |
102 | output = output_image("singleton_metaclass.png")
103 | #plt.show()
104 | return output
--------------------------------------------------------------------------------
/pydesignpatterns/creational/singleton_decorator.py:
--------------------------------------------------------------------------------
1 | """
2 | Author: CHIRAG SHAH
3 | Created On: 7th July 2018
4 | """
5 |
6 | import inspect, sys
7 | import matplotlib.pyplot as plt
8 | from pathlib import Path
9 |
10 | sys.path.append(str(Path(__file__).resolve().parent.parent))
11 | from utility import class_diagram, output_image
12 |
13 | class SingletonDecorated(object):
14 | """
15 | SingletonDecorated class is a naive implementation of Singleton pattern by using decorators
16 | __init__: doesn't return anything; it's only responsible for initializing the instance after it's been created
17 | __call__: this method is called when the instance is called, it allows to return arbitary values
18 |
19 | @return-values: instance of class
20 | """
21 |
22 | def __init__(self, decorated):
23 | self._decorated = decorated
24 |
25 | def instance(self):
26 | try:
27 | return self._instance
28 | except AttributeError:
29 | self._instance = self._decorated()
30 | return self._instance
31 |
32 | def __call__(self):
33 | raise TypeError('Singleton should be accessed through instance method.')
34 |
35 | def __instancecheck__(self, ins):
36 | return isinstance(ins, self._decorated)
37 |
38 | @SingletonDecorated
39 | class VeniVediVici:
40 | """
41 | Using singleton decorator to wrap around functionalities of Singleton pattern for this class
42 | """
43 |
44 | def __init__(self):
45 | print("Veni Vedi Vici means `he came, he saw, he conquered`")
46 |
47 |
48 | #------------------Log Starts------------------#
49 | def wrapperaround():
50 | #Using this function and nested class for sole purpose of get_code() function results
51 | #@SingletonDecorated --> Uncomment this line to understand this decorated class
52 |
53 | class VeniVediVici2:
54 | """
55 | Using singleton decorator to wrap around functionalities of Singleton pattern for this class
56 | """
57 | def __init__(self):
58 | print("Veni Vedi Vici means `he came, he saw, he conquered`")
59 | #-----------------Log Ends------------------#
60 |
61 |
62 | def test_decorated():
63 | """
64 | Showcases how decorators can be used in Singleton Pattern
65 | """
66 |
67 | #u = VeniVediVici() #Error raised --> Uncomment this line to see the error
68 | v = VeniVediVici.instance()
69 | w = VeniVediVici.instance()
70 | print(v is w)
71 |
72 | def get_code():
73 | """
74 | @return-values: source code
75 | """
76 |
77 | a = inspect.getsource(SingletonDecorated)
78 | b = inspect.getsource(wrapperaround)
79 | c = inspect.getsource(test_decorated)
80 | return a + '\n' + b + '\n' + c
81 |
82 | def get_classdiagram():
83 | """
84 | @return-values: matplotlib object with class diagram
85 | """
86 |
87 | diagram = class_diagram("singleton.png")
88 | #plt.show()
89 | return diagram
90 |
91 |
92 | def get_outputimage():
93 | """
94 | @return-values: matplotlib object with code output
95 | """
96 |
97 | output = output_image("singleton_decorated.png")
98 | #plt.show()
99 | return output
--------------------------------------------------------------------------------
/pydesignpatterns/creational/prototype_naive.py:
--------------------------------------------------------------------------------
1 | """
2 | Author: CHIRAG SHAH
3 | Created On: 21st September 2018
4 | """
5 |
6 | import inspect, sys, copy
7 | import matplotlib.pyplot as plt
8 | from pathlib import Path
9 | from abc import ABCMeta, abstractmethod
10 |
11 | sys.path.append(str(Path(__file__).resolve().parent.parent))
12 | from utility import class_diagram, output_image
13 |
14 |
15 | class Prototype:
16 |
17 | """ Object, that can be cloned.
18 | This is just a base class, so the clone() method
19 | is not implemented. But all subclasses have to
20 | override it.
21 | """
22 |
23 | _type = None
24 | _value = None
25 |
26 | def clone(self):
27 | pass
28 |
29 | def getType(self):
30 | return self._type
31 |
32 | def getValue(self):
33 | return self._value
34 |
35 | class Type1(Prototype):
36 |
37 | """ Concrete prototype.
38 | Implementation of Prototype. Important part is the
39 | clone() method.
40 | """
41 |
42 | def __init__(self, number):
43 | self._type = "Type1"
44 | self._value = number
45 |
46 | def clone(self):
47 | return copy.copy(self)
48 |
49 | class Type2(Prototype):
50 | """ Concrete prototype. """
51 |
52 | def __init__(self, number):
53 | self._type = "Type2"
54 | self._value = number
55 |
56 | def clone(self):
57 | return copy.copy(self)
58 |
59 | class ObjectFactory:
60 |
61 | """ Manages prototypes.
62 | Static factory, that encapsulates prototype
63 | initialization and then allows instatiation
64 | of the classes from these prototypes.
65 | """
66 |
67 | __type1Value1 = None
68 | __type2Value1 = None
69 |
70 | @staticmethod
71 | def initialize():
72 | ObjectFactory.__type1Value1 = Type1(1)
73 | ObjectFactory.__type2Value1 = Type2(1)
74 |
75 | @staticmethod
76 | def getType1Value1():
77 | return ObjectFactory.__type1Value1.clone()
78 |
79 | @staticmethod
80 | def getType2Value1():
81 | return ObjectFactory.__type2Value1.clone()
82 |
83 |
84 | def test_prototype():
85 | ObjectFactory.initialize()
86 |
87 | instance = ObjectFactory.getType1Value1()
88 | print("%s: %s" % (instance.getType(), instance.getValue()))
89 |
90 | instance = ObjectFactory.getType2Value1()
91 | print("%s: %s" % (instance.getType(), instance.getValue()))
92 |
93 | def get_code():
94 | """
95 | @return-values: source code
96 | """
97 | a = inspect.getsource(Prototype)
98 | b = inspect.getsource(Type1)
99 | c = inspect.getsource(Type2)
100 | d = inspect.getsource(ObjectFactory)
101 | e = inspect.getsource(test_prototype)
102 |
103 | return a + '\n' + b + '\n' + c + '\n' + d + '\n' + e
104 |
105 | def get_classdiagram():
106 | """
107 | @return-values: matplotlib object with class diagram
108 | """
109 |
110 | diagram = class_diagram("prototype.png")
111 | plt.show()
112 | return diagram
113 |
114 | def get_outputimage():
115 | """
116 | @return-values: matplotlib object with code output
117 | """
118 |
119 | output = output_image("prototype_naive.png")
120 | plt.show()
121 | return output
122 |
123 | test_prototype()
--------------------------------------------------------------------------------
/pydesignpatterns/creational/prototype_shape.py:
--------------------------------------------------------------------------------
1 | """
2 | Author: CHIRAG SHAH
3 | Created On: 20th September 2018
4 | """
5 |
6 | import inspect, sys, copy
7 | import matplotlib.pyplot as plt
8 | from pathlib import Path
9 | from abc import ABCMeta, abstractmethod
10 |
11 | sys.path.append(str(Path(__file__).resolve().parent.parent))
12 | from utility import class_diagram, output_image
13 |
14 | class Shape(metaclass = ABCMeta):
15 | """
16 | Abstract class
17 | """
18 | def __init__(self):
19 | self.id = None
20 | self.type = None
21 |
22 | @abstractmethod
23 | def draw(self):
24 | pass
25 |
26 | def get_type(self):
27 | return self.type
28 |
29 | def get_id(self):
30 | return self.id
31 |
32 | def set_id(self, id):
33 | self.id = id
34 |
35 | def clone(self):
36 | return copy.copy(self)
37 |
38 | class Rectangle(Shape):
39 | """
40 | Concrete class extending base class
41 | """
42 |
43 | def __init__(self):
44 | super().__init__()
45 | self.type = "Rectangle"
46 |
47 | def draw(self):
48 | print("Drawing Rectangle with draw()..")
49 |
50 | class Circle(Shape):
51 | """
52 | Concrete class extending base class
53 | """
54 |
55 | def __init__(self):
56 | super().__init__()
57 | self.type = "Circle"
58 |
59 | def draw(self):
60 | print("Drawing Circle with draw()..")
61 |
62 | class Square(Shape):
63 | """
64 | Concrete class extending base class
65 | """
66 |
67 | def __init__(self):
68 | super().__init__()
69 | self.type = "Square"
70 |
71 | def draw(self):
72 | print("Drawing Square with draw()..")
73 |
74 | class ShapeCacheAddr:
75 | """
76 | Maps classes with their id's in dict.
77 | Returns object clones when needed
78 | """
79 | cache = {}
80 |
81 | @staticmethod
82 | def get_shape(shape_id):
83 | shape = ShapeCacheAddr.cache.get(shape_id, None)
84 | return shape.clone()
85 |
86 | @staticmethod
87 | def load():
88 | circle = Circle()
89 | circle.set_id("1")
90 | ShapeCacheAddr.cache[circle.get_id()] = circle
91 |
92 | square = Square()
93 | square.set_id("2")
94 | ShapeCacheAddr.cache[square.get_id()] = square
95 |
96 | rectangle = Rectangle()
97 | rectangle.set_id("3")
98 | ShapeCacheAddr.cache[rectangle.get_id()] = rectangle
99 |
100 | def test_prototype():
101 | """
102 | Demonstration of prototype pattern
103 | """
104 |
105 | ShapeCacheAddr.load()
106 | circle = ShapeCacheAddr.get_shape("1")
107 | print(circle.get_type())
108 |
109 | square = ShapeCacheAddr.get_shape("2")
110 | print(square.get_type())
111 |
112 | rectangle = ShapeCacheAddr.get_shape("3")
113 | print(rectangle.get_type())
114 |
115 | def get_code():
116 | """
117 | @return-values: source code
118 | """
119 | a = inspect.getsource(Shape)
120 | b = inspect.getsource(Circle)
121 | c = inspect.getsource(Square)
122 | d = inspect.getsource(Rectangle)
123 | e = inspect.getsource(ShapeCacheAddr)
124 | f = inspect.getsource(test_prototype)
125 |
126 | return a + '\n' + b + '\n' + c + '\n' + d + '\n' + e + '\n' + f
127 |
128 | def get_classdiagram():
129 | """
130 | @return-values: matplotlib object with class diagram
131 | """
132 |
133 | diagram = class_diagram("prototype.png")
134 | plt.show()
135 | return diagram
136 |
137 | def get_outputimage():
138 | """
139 | @return-values: matplotlib object with code output
140 | """
141 |
142 | output = output_image("prototype_shape.png")
143 | plt.show()
144 | return output
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | Pydesignpatterns
2 | ================
3 |
4 | ## Python module to learn all design patterns on the go!
5 |
6 | - Reworking on each pattern after 2 years, Lets start again, one at a time! :grin:
7 |
8 | ### Todo
9 |
10 | - [x] Creational Design Patterns
11 | - [x] Singleton
12 | - [x] [Generic](https://github.com/avidLearnerInProgress/design-patterns/blob/master/pydesignpatterns/creational/singleton_naive.py)
13 | - [x] [Lazy instantiation](https://github.com/avidLearnerInProgress/design-patterns/blob/master/pydesignpatterns/creational/singleton_lazy_instantiation.py)
14 | - [x] [Decorated](https://github.com/avidLearnerInProgress/design-patterns/blob/master/pydesignpatterns/creational/singleton_decorator.py)
15 | - [x] [Metaclass](https://github.com/avidLearnerInProgress/design-patterns/blob/master/pydesignpatterns/creational/singleton_metaclass.py)
16 | - [x] [Threaded](https://github.com/avidLearnerInProgress/design-patterns/blob/master/pydesignpatterns/creational/singleton_thread.py)
17 | - [x] **Example:** *[Counter](https://github.com/avidLearnerInProgress/design-patterns/blob/master/pydesignpatterns/creational/singleton_counter.py)*
18 | - [x] Simple Factory
19 | - [x] [Generic](https://github.com/avidLearnerInProgress/design-patterns/blob/master/pydesignpatterns/creational/simplefactory_naive.py)
20 | - [x] **Examples:**
21 | - [x] *[Pizza](https://github.com/avidLearnerInProgress/design-patterns/blob/master/pydesignpatterns/creational/simplefactory_pizza.py)*
22 | - [x] *[Burger](https://github.com/avidLearnerInProgress/design-patterns/blob/master/pydesignpatterns/creational/simplefactory_burger.py)*
23 | - [x] Factory Method
24 | - [x] [Generic](https://github.com/avidLearnerInProgress/design-patterns/blob/master/pydesignpatterns/creational/factorymethod_naive.py)
25 | - [x] **Examples:**
26 | - [x] *[Car](https://github.com/avidLearnerInProgress/design-patterns/blob/master/pydesignpatterns/creational/factorymethod_car.py)*
27 | - [x] *[Cellphone](https://github.com/avidLearnerInProgress/design-patterns/blob/master/pydesignpatterns/creational/factorymethod_cellphone.py)*
28 | - [x] Abstract Factory
29 | - [x] [Generic](https://github.com/avidLearnerInProgress/design-patterns/blob/master/pydesignpatterns/creational/abstractfactory_naive.py)
30 | - [x] **Example:** *[Shape](https://github.com/avidLearnerInProgress/design-patterns/blob/master/pydesignpatterns/creational/abstractfactory_shape.py)*
31 | - [x] Builder
32 | - [x] [Generic](https://github.com/avidLearnerInProgress/design-patterns/blob/master/pydesignpatterns/creational/builder_naive.py)
33 | - [x] **Example:** *[Aircraft](https://github.com/avidLearnerInProgress/design-patterns/blob/master/pydesignpatterns/creational/builder_aircraft.py)*
34 | - [x] Prototype
35 | - [x] [Generic](https://github.com/avidLearnerInProgress/design-patterns/blob/master/pydesignpatterns/creational/prototype_naive.py)
36 | - [x] **Example:** *[Shape](https://github.com/avidLearnerInProgress/design-patterns/blob/master/pydesignpatterns/creational/prototype_shape.py)*
37 |
38 | - [ ] Behavioral Design Patterns
39 | - [ ] Chain Of Responsibility
40 | - [ ] [Generic]()
41 | - [x] **Example:** *[Planet](https://github.com/avidLearnerInProgress/design-patterns/blob/master/pydesignpatterns/behavioral/chain_of_responsibility_planet.py)*
42 |
43 |
44 | - [ ] Structural Design Patterns
45 | - [ ] Concurrency Design Patterns
46 |
47 |
48 | #### Inspired by [Omkar Pathak's](https://github.com/OmkarPathak/) [pygorithm](https://github.com/OmkarPathak/pygorithm)
49 |
50 |
--------------------------------------------------------------------------------
/tests/test_singleton.py:
--------------------------------------------------------------------------------
1 | """
2 | Author: CHIRAG SHAH
3 | Created On: 7th July 2018
4 | Modified On: 16th July 2018
5 | """
6 |
7 | import unittest, sys, inspect
8 | from pathlib import Path
9 |
10 |
11 | ROOT_DIR = str(Path(__file__).resolve().parent.parent)
12 | sys.path.append(ROOT_DIR)
13 |
14 | from pydesignpatterns.creational import (
15 | singleton_naive,
16 | singleton_lazy_instantiation,
17 | singleton_decorator,
18 | singleton_thread,
19 | singleton_metaclass,
20 | singleton_counter
21 | )
22 |
23 | class TestSingleton(unittest.TestCase):
24 |
25 | def test_class(self):
26 | self.assertEqual(inspect.isclass(singleton_naive.Singleton), True)
27 |
28 | def test_instances(self):
29 | s1, hs1 = singleton_naive.Singleton()
30 | s2, hs2 = singleton_naive.Singleton()
31 | self.assertEqual(id(s1), id(s2))
32 |
33 | def test_hashes(self):
34 | s1, hs1 = singleton_naive.Singleton()
35 | s2, hs2 = singleton_naive.Singleton()
36 | self.assertEqual(hs1, hs2)
37 |
38 | class TestSingletonLazy(unittest.TestCase):
39 |
40 | def test_class(self):
41 | self.assertEqual(inspect.isclass(singleton_lazy_instantiation.SingletonLazy), True)
42 |
43 | def test_instances(self):
44 | s1 = singleton_lazy_instantiation.SingletonLazy().get_instance()
45 | s2 = singleton_lazy_instantiation.SingletonLazy().get_instance()
46 | self.assertEqual(s1, s2)
47 | self.assertEqual(id(s1), id(s2))
48 |
49 | def test_lazy_instantiation(self):
50 | s1 = singleton_lazy_instantiation.SingletonLazy().get_instance()
51 | s2 = singleton_lazy_instantiation.SingletonLazy()
52 | self.assertNotEqual(s1, s2)
53 |
54 | class TestSingletonDecorated(unittest.TestCase):
55 |
56 | def test_class(self):
57 | self.assertEqual(inspect.isclass(singleton_decorator.SingletonDecorated), True)
58 |
59 | def test_instances(self):
60 | s1 = lambda: singleton_decorator.VeniVediVici().instance()
61 | s2 = lambda: singleton_decorator.VeniVediVici().instance()
62 | self.assertEqual(isinstance(s1, singleton_decorator.SingletonDecorated), isinstance(s2, singleton_decorator.SingletonDecorated))
63 |
64 | def test_instance_exception(self):
65 | self.assertRaises(TypeError, lambda: singleton_decorator.VeniVediVici())
66 |
67 | class TestSingletonThreaded(unittest.TestCase):
68 |
69 | def test_class(self):
70 | self.assertEqual(inspect.isclass(singleton_thread.SingletonThread), True)
71 |
72 | def test_instances(self):
73 | print("\n")
74 | s1 = singleton_thread.SingletonThread().get_instance()
75 | s2 = singleton_thread.SingletonThread().get_instance()
76 | self.assertEqual(s1, s2)
77 |
78 | def test_threadsafe(self):
79 | ts1 = singleton_thread.SingletonThread().get_instance().gettid()
80 | ts2 = singleton_thread.SingletonThread().get_instance().gettid()
81 | self.assertEqual(ts1, ts2)
82 |
83 | class TestSingletonMetaClass(unittest.TestCase):
84 |
85 | def test_class(self):
86 | self.assertEqual(inspect.isclass(singleton_metaclass.SingletonMetaclass), True)
87 |
88 | def test_instances(self):
89 | self.assertEqual(isinstance(singleton_metaclass.A, singleton_metaclass.SingletonMetaclass), isinstance(singleton_metaclass.B, singleton_metaclass.SingletonMetaclass))
90 |
91 | class TestSingletonCounter(unittest.TestCase):
92 |
93 | def test_class(self):
94 | self.assertEqual(inspect.isclass(singleton_counter.SingletonCounter), True)
95 |
96 | def test_instances(self):
97 | s1 = singleton_counter.SingletonCounter.get_instance()
98 | s2 = singleton_counter.SingletonCounter.get_instance()
99 | self.assertEqual(s1, s2)
100 |
101 | def test_count(self):
102 | s1 = singleton_counter.SingletonCounter.get_instance()
103 | self.assertEqual(s1.get_count(), 1)
104 | s2 = singleton_counter.SingletonCounter.get_instance()
105 | self.assertEqual(s2.get_count(), 2)
--------------------------------------------------------------------------------
/pydesignpatterns/creational/simplefactory_naive.py:
--------------------------------------------------------------------------------
1 | """
2 | Author: CHIRAG SHAH
3 | Created On: 15th July 2018
4 | """
5 |
6 | import inspect, sys
7 | import matplotlib.pyplot as plt
8 | from pathlib import Path
9 | from abc import ABCMeta, abstractmethod
10 |
11 | sys.path.append(str(Path(__file__).resolve().parent.parent))
12 | from utility import class_diagram, output_image
13 |
14 | class AbstractProduct(metaclass = ABCMeta):
15 | """
16 | Abstract base class with __init__ as the abstract method
17 | Used for inheritance by different types of products
18 |
19 | @return-values: name of product
20 | """
21 |
22 | @abstractmethod
23 | def __init__(self):
24 | pass
25 |
26 | def get_product(self):
27 | return self._name
28 | #do something else..
29 |
30 | class ProductFactory:
31 | """
32 | Factory interface class used for selecting type of product
33 | Here we use the ideal concept of factory design pattern by hiding the object creation logic from the client
34 |
35 | @return-values: instance of product type selected by user
36 | """
37 |
38 | @staticmethod
39 | def create_product(p_type):
40 | product = None
41 |
42 | if p_type == "product 1":
43 | product = Product1()
44 | elif p_type == "product 2":
45 | product = Product2()
46 |
47 | return product
48 |
49 | class Product1(AbstractProduct):
50 | """
51 | Class used for customising the type of product needed by client / provided by store to client
52 | Here we use the abstract method __init__ to set the product attributes
53 |
54 | @params: class to inherit
55 | """
56 |
57 | def __init__(self):
58 | super(Product1, self).__init__()
59 | self._name = "I am Product A"
60 |
61 | #do something else
62 |
63 |
64 | class Product2(AbstractProduct):
65 | """
66 | Class used for customising the type of product needed by client / provided by store to client
67 | Here we use the abstract method __init__ to set the product attributes
68 |
69 | @params: class to inherit
70 | """
71 |
72 | def __init__(self):
73 | super(Product2, self).__init__()
74 | self._name = "I am Product B"
75 |
76 | #do something else
77 |
78 | class Client:
79 | """
80 | Class which interacts with the client to order his product
81 | Here we initialise the factory class which serves the functionality of creating instances
82 |
83 | @return-values: Product delivered to client
84 | """
85 |
86 | def __init__(self, factory):
87 | self._factory = factory
88 |
89 | def order_product(self, p_type= None):
90 | if p_type is None:
91 | p_type = "product 2"
92 | order = ProductFactory.create_product(p_type)
93 | return order
94 |
95 | def test_factory():
96 | """
97 | Demonstration of factory pattern
98 | """
99 |
100 | factory = ProductFactory()
101 | store = Client(factory)
102 | product = store.order_product("product 1")
103 | print("----" + product.get_product() + "----")
104 |
105 | product = store.order_product()
106 | print("----" + product.get_product() + "----")
107 |
108 | def get_code():
109 | """
110 | @return-values: source code
111 | """
112 |
113 | a = inspect.getsource(AbstractProduct)
114 | b = inspect.getsource(ProductFactory)
115 | c = inspect.getsource(Product1)
116 | d = inspect.getsource(Product2)
117 | e = inspect.getsource(Client)
118 | f = inspect.getsource(test_factory)
119 | return a + '\n' + b + '\n' + c + '\n' + d + '\n' + e + '\n' + f
120 |
121 | def get_classdiagram():
122 | """
123 | @return-values: matplotlib object with class diagram
124 | """
125 |
126 | diagram = class_diagram("simplefactory.png")
127 | #plt.show()
128 | return diagram
129 |
130 | def get_outputimage():
131 | """
132 | @return-values: matplotlib object with code output
133 | """
134 |
135 | output = output_image("simplefactory_naive.png")
136 | #plt.show()
137 | return output
--------------------------------------------------------------------------------
/pydesignpatterns/creational/factorymethod_naive.py:
--------------------------------------------------------------------------------
1 | """
2 | Author: CHIRAG SHAH
3 | Created On: 19th July 2018
4 | """
5 |
6 | import inspect, sys
7 | import matplotlib.pyplot as plt
8 | from pathlib import Path
9 | from abc import ABCMeta, abstractmethod
10 |
11 | sys.path.append(str(Path(__file__).resolve().parent.parent))
12 | from utility import class_diagram, output_image
13 |
14 | class AbstractCreator(metaclass = ABCMeta):
15 | """
16 | Abstract base class with __init__ as the abstract method
17 | Used for inheritance by different types of ConcreteCreators
18 |
19 | @return-values: name of creator
20 | """
21 |
22 |
23 | def __init__(self):
24 | self.product = self.factory_method()
25 |
26 | @abstractmethod
27 | def factory_method(self):
28 | pass
29 |
30 | #Logging functions
31 | def log(self):
32 | #self.product.interface()
33 | pass
34 |
35 | class ConcreteCreatorA(AbstractCreator):
36 | """
37 | Class used for customising the type of creator needed by client / provided by store to client
38 | Here we use the abstract method __init__ to set the concretecreator attributes
39 |
40 | @params: class to inherit
41 | """
42 |
43 | def factory_method(self):
44 | return ConcreteProductA()
45 |
46 | class ConcreteCreatorB(AbstractCreator):
47 | """
48 | Class used for customising the type of creator needed by client / provided by store to client
49 | Here we use the abstract method __init__ to set the concretecreator attributes
50 |
51 | @params: class to inherit
52 | """
53 |
54 | def factory_method(self):
55 | return ConcreteProductB()
56 |
57 | class AbstractProduct(metaclass = ABCMeta):
58 | """
59 | Abstract Interface for creating objects
60 | Here we do not instantiate the object but pass the instantiation to further subclasses
61 |
62 | @return-values: Complete product delivered to client
63 | """
64 |
65 | @abstractmethod
66 | def interface(self):
67 | pass
68 |
69 | class ConcreteProductA(AbstractProduct):
70 | """
71 | Subclass of the product factory for instantiating appropriate concretecreator object
72 | Here we use the ideal concept of factorymethod design pattern by allowing the subclass to initialise the class
73 |
74 | @return-values: instance of concretecreator
75 | """
76 |
77 | def interface(self):
78 | return "I am in A"
79 |
80 | class ConcreteProductB(AbstractProduct):
81 | """
82 | Subclass of the product factory for instantiating appropriate concretecreator object
83 | Here we use the ideal concept of factorymethod design pattern by allowing the subclass to initialise the class
84 |
85 | @return-values: instance of concretecreator
86 | """
87 |
88 | def interface(self):
89 | return "I am in B"
90 |
91 |
92 | def test_factory():
93 | """
94 | Demonstration of factorymethod pattern
95 | """
96 |
97 | concretecreator = ConcreteCreatorA()
98 | concretecreator.product.interface()
99 | #concretecreator.log()
100 |
101 | def get_code():
102 | """
103 | @return-values: source code
104 | """
105 |
106 | a = inspect.getsource(AbstractCreator)
107 | b = inspect.getsource(ConcreteCreatorA)
108 | c = inspect.getsource(ConcreteCreatorB)
109 | d = inspect.getsource(AbstractProduct)
110 | e = inspect.getsource(ConcreteProductA)
111 | f = inspect.getsource(ConcreteProductB)
112 | g = inspect.getsource(test_factory)
113 |
114 | return a + '\n' + b + '\n' + c + '\n' + d + '\n' + e + '\n' + f + '\n' + g
115 |
116 | def get_classdiagram():
117 | """
118 | @return-values: matplotlib object with class diagram
119 | """
120 |
121 | diagram = class_diagram("factorymethod.png")
122 | #plt.show()
123 | return diagram
124 |
125 | def get_outputimage():
126 | """
127 | @return-values: matplotlib object with code output
128 | """
129 |
130 | output = output_image("factorymethod_naive.png")
131 | #plt.show()
132 | return output
--------------------------------------------------------------------------------
/pydesignpatterns/creational/abstractfactory_naive.py:
--------------------------------------------------------------------------------
1 | """
2 | Author: CHIRAG SHAH
3 | Created On: 23th July 2018
4 | """
5 |
6 | import inspect, sys
7 | import matplotlib.pyplot as plt
8 | from pathlib import Path
9 | from abc import ABCMeta, abstractmethod
10 |
11 | sys.path.append(str(Path(__file__).resolve().parent.parent))
12 | from utility import class_diagram, output_image
13 |
14 | class AbstractFactory(metaclass = ABCMeta):
15 | """
16 | Declares an interface for creating abstract products
17 | """
18 |
19 |
20 | @abstractmethod
21 | def create_product_a(self):
22 | pass
23 |
24 | @abstractmethod
25 | def create_product_b(self):
26 | pass
27 |
28 |
29 | class ConcreteFactory1(AbstractFactory):
30 | """
31 | Implement operations to create concrete products
32 |
33 | @return-values: instance of concrete product
34 | """
35 |
36 | def create_product_a(self):
37 | return ConcreteProductA1()
38 |
39 | def create_product_b(self):
40 | return ConcreteProductB1()
41 |
42 | class ConcreteFactory2(AbstractFactory):
43 | """
44 | Implement operations to create concrete products
45 |
46 | @return-values: instance of concrete product
47 | """
48 |
49 | def create_product_a(self):
50 | return ConcreteProductA2()
51 |
52 | def create_product_b(self):
53 | return ConcreteProductB2()
54 |
55 | class AbstractProductA(metaclass = ABCMeta):
56 | """
57 | Declares interface for type of product
58 | """
59 |
60 | @abstractmethod
61 | def interface_a(self):
62 | pass
63 |
64 | class AbstractProductB(metaclass = ABCMeta):
65 | """
66 | Declares interface for type of product
67 | """
68 |
69 | @abstractmethod
70 | def interface_b(self):
71 | pass
72 |
73 | class ConcreteProductA1(AbstractProductA):
74 | """
75 | Define a product object to be created by the corresponding concrete
76 | factory.
77 | """
78 |
79 | def interface_a(self):
80 | return "I am in A1"
81 |
82 | class ConcreteProductA2(AbstractProductA):
83 | """
84 | Define a product object to be created by the corresponding concrete
85 | factory.
86 | """
87 |
88 | def interface_a(self):
89 | return "I am in A2"
90 |
91 | class ConcreteProductB1(AbstractProductB):
92 | """
93 | Define a product object to be created by the corresponding concrete
94 | factory.
95 | """
96 |
97 | def interface_b(self):
98 | return "I am in B1"
99 |
100 | class ConcreteProductB2(AbstractProductB):
101 | """
102 | Define a product object to be created by the corresponding concrete
103 | factory.
104 | """
105 |
106 | def interface_b(self):
107 | return "I am in B2"
108 |
109 | def test_factory():
110 | """
111 | Demonstration of abstractfactory pattern
112 | """
113 |
114 | for factory in (ConcreteFactory1(), ConcreteFactory2()):
115 | p_a = factory.create_product_a()
116 | p_b = factory.create_product_b()
117 | print(p_a.interface_a())
118 | print(p_b.interface_b())
119 |
120 | def get_code():
121 | """
122 | @return-values: source code
123 | """
124 |
125 | a = inspect.getsource(AbstractFactory)
126 | b = inspect.getsource(ConcreteFactory1)
127 | c = inspect.getsource(ConcreteFactory2)
128 | d = inspect.getsource(AbstractProductA)
129 | e = inspect.getsource(AbstractProductB)
130 | f = inspect.getsource(ConcreteProductA1)
131 | g = inspect.getsource(ConcreteProductA2)
132 | h = inspect.getsource(ConcreteProductB1)
133 | i = inspect.getsource(ConcreteProductB2)
134 | j = inspect.getsource(test_factory)
135 |
136 | return a + '\n' + b + '\n' + c + '\n' + d + '\n' + e + '\n' + f + '\n' + g + '\n' + h + '\n' + i + '\n' + j
137 |
138 | def get_classdiagram():
139 | """
140 | @return-values: matplotlib object with class diagram
141 | """
142 |
143 | diagram = class_diagram("abstractfactory.png")
144 | plt.show()
145 | return diagram
146 |
147 | def get_outputimage():
148 | """
149 | @return-values: matplotlib object with code output
150 | """
151 |
152 | output = output_image("abstractfactory_naive.png")
153 | plt.show()
154 | return output
--------------------------------------------------------------------------------
/pydesignpatterns/creational/builder_aircraft.py:
--------------------------------------------------------------------------------
1 | """
2 | Author: CHIRAG SHAH
3 | Created On: 26th July 2018
4 | """
5 |
6 | import inspect, sys
7 | import matplotlib.pyplot as plt
8 | from pathlib import Path
9 | from abc import ABCMeta, abstractmethod
10 |
11 | sys.path.append(str(Path(__file__).resolve().parent.parent))
12 | from utility import class_diagram, output_image
13 |
14 | class Aircraft:
15 | """
16 | Base initialisation object
17 | """
18 |
19 | mark = ''
20 | model = ''
21 | max_speed = 0
22 | takeoff_speed = 0
23 | passengers_count = 0
24 | fuel_capacity = 0
25 |
26 | class AircraftBuilder(metaclass = ABCMeta):
27 | """
28 | Abstract builder for creating aircraft
29 | """
30 |
31 | def __init__(self):
32 | self.aircraft = None
33 |
34 | def create_aircraft(self):
35 | self.aircraft = Aircraft()
36 |
37 | @abstractmethod
38 | def build_mark(self):
39 | pass
40 |
41 | @abstractmethod
42 | def build_model(self):
43 | pass
44 |
45 | @abstractmethod
46 | def build_max_speed(self):
47 | pass
48 |
49 | @abstractmethod
50 | def build_takeoff_speed(self):
51 | pass
52 |
53 | @abstractmethod
54 | def build_passengers_count(self):
55 | pass
56 |
57 | @abstractmethod
58 | def build_fuel_capacity(self):
59 | pass
60 |
61 | class Airbus380Builder(AircraftBuilder):
62 | """
63 | Concrete aircraft builder used for constructing the attributes of aircraft by inheriting the abstract builder
64 | """
65 |
66 | def build_fuel_capacity(self):
67 | self.aircraft.fuel_capacity = 32000
68 |
69 | def build_takeoff_speed(self):
70 | self.aircraft.takeoff_speed = 277.8
71 |
72 | def build_max_speed(self):
73 | self.aircraft.max_speed = 1020
74 |
75 | def build_passengers_count(self):
76 | self.aircraft.passengers_count = 538
77 |
78 | def build_mark(self):
79 | self.aircraft.mark = 'Airbus'
80 |
81 | def build_model(self):
82 | self.aircraft.model = 'A-380'
83 |
84 | class Cessna172Builder(AircraftBuilder):
85 | """
86 | Concrete aircraft builder used for constructing the attributes of aircraft by inheriting the abstract builder
87 | """
88 |
89 | def build_fuel_capacity(self):
90 | self.aircraft.fuel_capacity = 249.837
91 |
92 | def build_takeoff_speed(self):
93 | self.aircraft.takeoff_speed = 277.8
94 |
95 | def build_max_speed(self):
96 | self.aircraft.max_speed = 302
97 |
98 | def build_passengers_count(self):
99 | self.aircraft.passengers_count = 1
100 |
101 | def build_mark(self):
102 | self.aircraft.mark = 'Cessna'
103 |
104 | def build_model(self):
105 | self.aircraft.model = '172'
106 |
107 | class AircraftDirector:
108 | """
109 | Constructs aircraft object using builder interface
110 | """
111 |
112 | def __init__(self):
113 | self._builder = None
114 |
115 | def build(self, aircraft_builder):
116 | self._builder = aircraft_builder
117 | self._builder.build_fuel_capacity()
118 | self._builder.build_takeoff_speed()
119 | self._builder.build_max_speed()
120 | self._builder.build_passengers_count()
121 | self._builder.build_mark()
122 | self._builder.build_model()
123 | return self._builder.aircraft
124 |
125 | def get_custom_fields_str(obj):
126 | return '\n'.join('{}: {}'.format(field, obj.__getattribute__(field)) for field in dir(obj) if not field.startswith('__'))
127 |
128 | def test_builder():
129 | """
130 | Demonstration of builder pattern
131 | """
132 |
133 | aircraft_builder = Airbus380Builder()
134 | aircraft_builder.create_aircraft()
135 | aircraft_director = AircraftDirector()
136 | aircraft = aircraft_director.build(aircraft_builder)
137 | #print(get_custom_fields_str(aircraft))
138 |
139 | def get_code():
140 | """
141 | @return-values: source code
142 | """
143 | a = inspect.getsource(Aircraft)
144 | b = inspect.getsource(AircraftBuilder)
145 | c = inspect.getsource(Airbus380Builder)
146 | d = inspect.getsource(Cessna172Builder)
147 | e = inspect.getsource(AircraftDirector)
148 | f = inspect.getsource(test_builder)
149 |
150 | return a + '\n' + b + '\n' + c + '\n' + d + '\n' + e + '\n' + f
151 |
152 | def get_classdiagram():
153 | """
154 | @return-values: matplotlib object with class diagram
155 | """
156 |
157 | diagram = class_diagram("builder.png")
158 | plt.show()
159 | return diagram
160 |
161 | def get_outputimage():
162 | """
163 | @return-values: matplotlib object with code output
164 | """
165 |
166 | output = output_image("builder_aircraft.png")
167 | plt.show()
168 | return output
169 |
170 | test_builder()
--------------------------------------------------------------------------------
/pydesignpatterns/behavioral/chain_of_responsibility_planet.py:
--------------------------------------------------------------------------------
1 | """
2 | Author: CHIRAG SHAH
3 | Created On: 16th October 2018
4 | """
5 |
6 | import inspect, sys
7 | import matplotlib.pyplot as plt
8 | from pathlib import Path
9 | from abc import ABCMeta, abstractmethod
10 | from enum import IntEnum
11 |
12 | sys.path.append(str(Path(__file__).resolve().parent.parent))
13 | from utility import class_diagram, output_image
14 |
15 | class PlanetEnum(IntEnum):
16 | """
17 | Setter class
18 | """
19 | MERCURY = 1
20 | VENUS = 2
21 | EARTH = 3
22 | MARS = 4
23 | JUPITER = 5
24 | SATURN = 6
25 | URANUS = 7
26 | NEPTUNE = 8
27 |
28 |
29 | '''
30 | Understanding:
31 | In this pattern, normally each receiver contains reference to another receiver. If one object cannot handle the request then it passes the same to the next receiver and so on. The first object in the chain receives the request and decides either to handle the request or to pass it on to the next object in the chain. The request flows through all objects in the chain one after the other until the request is handled by one of the handlers in the chain or the request reaches the end of the chain without getting processed.
32 | '''
33 | class PlanetHandler(metaclass=ABCMeta):
34 | """
35 | Abstract base class so that subclasses utilise the set_next_handler() and implement handle_request
36 | """
37 |
38 | def __init__(self):
39 | self.next_handler = None
40 |
41 | @abstractmethod
42 | def handle_request(self, request):
43 | pass
44 |
45 | def set_next_handler(self, handler):
46 | self.next_handler = handler
47 |
48 |
49 | class MercuryHandler(PlanetHandler):
50 | """
51 | Subclass
52 | """
53 |
54 | def handle_request(self, request):
55 | if request is PlanetEnum.MERCURY:
56 | print("MercuryHandler handles " + request.name)
57 | print("Mercury is hot.")
58 | else:
59 | print("MercuryHandler doesn't handle " + request.name)
60 | if self.next_handler is not None:
61 | self.next_handler.handle_request(request)
62 |
63 |
64 | class VenusHandler(PlanetHandler):
65 | """
66 | Subclass
67 | """
68 |
69 | def handle_request(self, request):
70 | if request is PlanetEnum.VENUS:
71 | print("VenusHandler handles " + request.name)
72 | print("Venus is poisonous.")
73 | else:
74 | print("VenusHandler doesn't handle " + request.name)
75 | if self.next_handler is not None:
76 | self.next_handler.handle_request(request)
77 |
78 |
79 | class EarthHandler(PlanetHandler):
80 | """
81 | Subclass
82 | """
83 |
84 | def handle_request(self, request):
85 | if request is PlanetEnum.EARTH:
86 | print("EarthHandler handles " + request.name)
87 | print("Earth is comfortable.")
88 | else:
89 | print("EarthHandler doesn't handle " + request.name)
90 | if self.next_handler is not None:
91 | self.next_handler.handle_request(request)
92 |
93 |
94 | def set_up_chain():
95 | mercury_handler = MercuryHandler()
96 | venus_handler = VenusHandler()
97 | earth_handler = EarthHandler()
98 | mercury_handler.set_next_handler(venus_handler)
99 | venus_handler.set_next_handler(earth_handler)
100 |
101 | return mercury_handler
102 |
103 |
104 | def test_chain_of_responsibility()
105 | chain = set_up_chain()
106 | chain.handle_request(PlanetEnum.VENUS)
107 | chain.handle_request(PlanetEnum.MERCURY)
108 | chain.handle_request(PlanetEnum.EARTH)
109 | chain.handle_request(PlanetEnum.JUPITER)
110 |
111 |
112 | def get_code():
113 | """
114 | @return-values: source code
115 | """
116 |
117 | a = inspect.getsource(PlanetEnum)
118 | b = inspect.getsource(PlanetHandler)
119 | c = inspect.getsource(MercuryHandler)
120 | d = inspect.getsource(VenusHandler)
121 | e = inspect.getsource(Earth)
122 | f = inspect.getsource(set_up_chain)
123 | g = inspect.getsource(test_chain_of_responsibility)
124 | return a + '\n' + b + '\n' + c + '\n' + d + '\n' + e + '\n' + f + '\n' + g
125 |
126 | def get_classdiagram():
127 | """
128 | @return-values: matplotlib object with class diagram
129 | """
130 |
131 | diagram = class_diagram("chainofresponsibility.png")
132 | plt.show()
133 | return diagram
134 |
135 | def get_outputimage():
136 | """
137 | @return-values: matplotlib object with code output
138 | """
139 |
140 | output = output_image("chainofresponsibility_planet.png")
141 | plt.show()
142 | return output
--------------------------------------------------------------------------------
/pydesignpatterns/creational/abstractfactory_shape.py:
--------------------------------------------------------------------------------
1 | """
2 | Author: CHIRAG SHAH
3 | Created On: 22th July 2018
4 | """
5 |
6 | import inspect, sys
7 | import matplotlib.pyplot as plt
8 | from pathlib import Path
9 | from abc import ABCMeta, abstractmethod
10 |
11 | sys.path.append(str(Path(__file__).resolve().parent.parent))
12 | from utility import class_diagram, output_image
13 |
14 | class DrawFactory(metaclass = ABCMeta):
15 | """
16 | Abstract Factory which creates families of related objects
17 | Used for inheritance by different concrete factories
18 | """
19 |
20 | @abstractmethod
21 | def create_shape(self):
22 | pass
23 |
24 | @abstractmethod
25 | def fill_shape(self):
26 | pass
27 |
28 | class CircleFactory(DrawFactory):
29 | """
30 | Concrete factory used to initialise the appropriate class
31 |
32 | @return-values: instance of class
33 | """
34 |
35 | def create_shape(self):
36 | return CircleShape()
37 |
38 | def fill_shape(self):
39 | return CircleColor()
40 |
41 | class TriangleFactory(DrawFactory):
42 | """
43 | Concrete factory used to initialise the appropriate class
44 |
45 | @return-values: instance of class
46 | """
47 |
48 | def create_shape(self):
49 | return TriangleShape()
50 |
51 | def fill_shape(self):
52 | return TriangleColor()
53 |
54 | class CreateShape(metaclass = ABCMeta):
55 | """
56 | Abstract Product which has to be inherited by concrete products
57 | """
58 | @abstractmethod
59 | def create(self, CreateShape):
60 | pass
61 |
62 | class FillShape(metaclass = ABCMeta):
63 | """
64 | Abstract Product which has to be inherited by concrete products
65 | """
66 |
67 | @abstractmethod
68 | def fill(self, CreateShape):
69 | pass
70 |
71 |
72 | class CircleShape(CreateShape):
73 | """
74 | Concrete product which implements abstract method from the abstrct product
75 | """
76 |
77 | def create(self):
78 | print("Creating circle shape using class: " + type(self).__name__)
79 |
80 | class CircleColor(FillShape):
81 | """
82 | Concrete product which implements abstract method from the abstrct product
83 | """
84 |
85 | def fill(self, CreateShape):
86 | print("Circle created, now filling shape using class: " + type(self).__name__)
87 |
88 | class TriangleShape(CreateShape):
89 | """
90 | Concrete product which implements abstract method from the abstrct product
91 | """
92 |
93 | def create(self):
94 | print("Creating triangle shape using class: " + type(self).__name__)
95 |
96 | class TriangleColor(FillShape):
97 | """
98 | Concrete product which implements abstract method from the abstrct product
99 | """
100 |
101 | def fill(self, CreateShape):
102 | print("Triangle created, now filling shape using class: " + type(self).__name__)
103 |
104 |
105 | class ShapeFactoryStore:
106 | """
107 | Class to interact with client
108 | """
109 | def __init__(self):
110 | pass
111 |
112 | def make_shape(self):
113 | for factory in [CircleFactory(), TriangleFactory()]:
114 | self.factory = factory
115 | self.createshape = self.factory.create_shape()
116 | self.fillshape = self.factory.fill_shape()
117 | self.createshape.create()
118 | self.fillshape.fill(self.createshape)
119 |
120 | def make_circle(self):
121 | self.factory = CircleFactory()
122 | self.createshape = self.factory.create_shape()
123 | self.fillshape = self.factory.fill_shape()
124 | self.createshape.create()
125 | self.fillshape.fill(self.createshape)
126 |
127 | def make_triangle(self):
128 | self.factory = TriangleFactory()
129 | self.createshape = self.factory.create_shape()
130 | self.fillshape = self.factory.fill_shape()
131 | self.createshape.create()
132 | self.fillshape.fill(self.createshape)
133 |
134 |
135 | def test_factory():
136 | """
137 | Demonstration of abstract factory pattern
138 | """
139 |
140 | shape = ShapeFactoryStore()
141 | shape.make_shape()
142 |
143 | def get_code():
144 | """
145 | @return-values: source code
146 | """
147 |
148 | a = inspect.getsource(DrawFactory)
149 | b = inspect.getsource(CircleFactory)
150 | c = inspect.getsource(TriangleFactory)
151 | d = inspect.getsource(CreateShape)
152 | e = inspect.getsource(FillShape)
153 | f = inspect.getsource(CircleShape)
154 | g = inspect.getsource(CircleColor)
155 | h = inspect.getsource(TriangleShape)
156 | i = inspect.getsource(TriangleColor)
157 | j = inspect.getsource(ShapeFactoryStore)
158 | k = inspect.getsource(test_factory)
159 | return a + '\n' + b + '\n' + c + '\n' + d + '\n' + e + '\n' + f + '\n' + g + '\n' + h + '\n' + i + '\n' + j + '\n' + k
160 |
161 | def get_classdiagram():
162 | """
163 | @return-values: matplotlib object with class diagram
164 | """
165 |
166 | diagram = class_diagram("abstractfactory.png")
167 | #plt.show()
168 | return diagram
169 |
170 | def get_outputimage():
171 | """
172 | @return-values: matplotlib object with code output
173 | """
174 |
175 | output = output_image("abstractfactory_shape.png")
176 | #plt.show()
177 | return output
178 |
--------------------------------------------------------------------------------
/pydesignpatterns/creational/simplefactory_burger.py:
--------------------------------------------------------------------------------
1 | """
2 | Author: CHIRAG SHAH
3 | Created On: 14th July 2018
4 | """
5 |
6 | import inspect, sys
7 | import matplotlib.pyplot as plt
8 | from pathlib import Path
9 | from abc import ABCMeta, abstractmethod
10 |
11 | sys.path.append(str(Path(__file__).resolve().parent.parent))
12 | from utility import class_diagram, output_image
13 |
14 | class Burger(metaclass = ABCMeta):
15 | """
16 | Abstract base class with __init__ as the abstract method
17 | Used for inheritance by different types of Burgers
18 |
19 | @return-values: name of burger
20 | """
21 |
22 | @abstractmethod
23 | def __init__(self):
24 | self._name = None
25 | self._bun = None
26 | self._sauce = None
27 | self._toppings = []
28 |
29 | def get_burgername(self):
30 | return self._name
31 |
32 | #Logging functions
33 | def assemble(self):
34 | print("Assembling all the ingrediets for..." + self._name)
35 |
36 | def prepare(self):
37 | print("Preparing..." + self._name)
38 | print("Choosing buns...")
39 | print("Adding sauce...")
40 | print("Adding toppings: ")
41 | print(", ".join(self._toppings))
42 |
43 | def pack(self):
44 | print("Packing with sauce...")
45 |
46 | class BurgerFactory:
47 | """
48 | Factory interface class used for selecting type of burger
49 | Here we use the ideal concept of factory design pattern by hiding the object creation logic from the client
50 |
51 | @return-values: instance of burger type selected by user
52 | """
53 |
54 |
55 | @staticmethod
56 | def create_burger(burger_type):
57 | burger = None
58 |
59 | if burger_type == "mixveggie":
60 | burger = MixVeggieBurger()
61 | elif burger_type == "grilledmushroom":
62 | burger = GrilledMushroomBurger()
63 | elif burger_type == "caramalizedonion":
64 | burger = CaramalizedOnionBurger()
65 | elif burger_type == "cheese":
66 | burger = CheeseBurger()
67 |
68 | return burger
69 |
70 | class MixVeggieBurger(Burger):
71 | """
72 | Class used for customising the type of burger needed by client / provided by store to client
73 | Here we use the abstract method __init__ to set the burger attributes
74 |
75 | @params: class to inherit
76 | """
77 |
78 | def __init__(self):
79 | super(MixVeggieBurger, self).__init__()
80 | self._name = "Mix Veggie"
81 | self._bun = "English Muffin"
82 | self._sauce = "Tomato"
83 | self._toppings.append("red onions")
84 | self._toppings.append("fresh spinach")
85 | self._toppings.append("garlic aioli")
86 | self._toppings.append("grilled pineapple")
87 |
88 | class GrilledMushroomBurger(Burger):
89 | """
90 | Class used for customising the type of burger needed by client / provided by store to client
91 | Here we use the abstract method __init__ to set the burger attributes
92 |
93 | @params: class to inherit
94 | """
95 |
96 | def __init__(self):
97 | super(GrilledMushroomBurger, self).__init__()
98 | self._name = "Grilled Mushroom"
99 | self._bun = "Kaiser Roll"
100 | self._sauce = "Apple"
101 | self._toppings.append("sliced cucumber")
102 | self._toppings.append("fresh lettuce")
103 | self._toppings.append("grilled pineapple")
104 | self._toppings.append("fresh gucamole")
105 |
106 | class CaramalizedOnionBurger(Burger):
107 | """
108 | Class used for customising the type of burger needed by client / provided by store to client
109 | Here we use the abstract method __init__ to set the burger attributes
110 |
111 | @params: class to inherit
112 | """
113 |
114 | def __init__(self):
115 | super(CaramalizedOnionBurger, self).__init__()
116 | self._name = "Caramalize Onion"
117 | self._bun = "Onion Roll"
118 | self._sauce = "Strawberry"
119 | self._toppings.append("sliced cucumber")
120 | self._toppings.append("fresh lettuce")
121 | self._toppings.append("garlic aioli")
122 | self._toppings.append("fresh spinach")
123 |
124 | class CheeseBurger(Burger):
125 | """
126 | Class used for customising the type of burger needed by client / provided by store to client
127 | Here we use the abstract method __init__ to set the burger attributes
128 |
129 | @params: class to inherit
130 | """
131 |
132 | def __init__(self):
133 | super(CheeseBurger, self).__init__()
134 | self._name = "Cheese"
135 | self._bun = "Potato Roll"
136 | self._sauce = "Tomato"
137 | self._toppings.append("red onions")
138 | self._toppings.append("feta style cheese")
139 | self._toppings.append("grilled pineapple")
140 | self._toppings.append("crunched sprouts")
141 |
142 | class BurgerStore:
143 | """
144 | Class which interacts with the client to order his burger
145 | Here we initialise the factory class which serves the functionality of creating instances
146 |
147 | @return-values: Complete burger delivered to client
148 | """
149 |
150 | def __init__(self, factory):
151 | self._factory = factory
152 |
153 | def order_burger(self, burger_type= None):
154 | if burger_type is None:
155 | burger_type = "mixveggie"
156 | burger = BurgerFactory.create_burger(burger_type)
157 | burger.assemble()
158 | burger.prepare()
159 | burger.pack()
160 | return burger
161 |
162 | def test_factory():
163 | """
164 | Demonstration of factory pattern
165 | """
166 |
167 | factory = BurgerFactory()
168 | store = BurgerStore(factory)
169 | burger = store.order_burger("mixveggie")
170 | print("Burger Ready: " + burger.get_burgername())
171 |
172 | def get_code():
173 | """
174 | @return-values: source code
175 | """
176 |
177 | a = inspect.getsource(Burger)
178 | b = inspect.getsource(BurgerFactory)
179 | c = inspect.getsource(MixVeggieBurger)
180 | d = inspect.getsource(GrilledMushroomBurger)
181 | e = inspect.getsource(CaramalizedOnionBurger)
182 | f = inspect.getsource(CheeseBurger)
183 | g = inspect.getsource(BurgerStore)
184 | h = inspect.getsource(test_factory)
185 | return a + '\n' + b + '\n' + c + '\n' + d + '\n' + e + '\n' + f + '\n' + g + '\n' + h
186 |
187 | def get_classdiagram():
188 | """
189 | @return-values: matplotlib object with class diagram
190 | """
191 |
192 | diagram = class_diagram("simplefactory.png")
193 | #plt.show()
194 | return diagram
195 |
196 | def get_outputimage():
197 | """
198 | @return-values: matplotlib object with code output
199 | """
200 |
201 | output = output_image("simplefactory_burger.png")
202 | #plt.show()
203 | return output
--------------------------------------------------------------------------------
/pydesignpatterns/creational/factorymethod_cellphone.py:
--------------------------------------------------------------------------------
1 | """
2 | Author: CHIRAG SHAH
3 | Created On: 19th July 2018
4 | """
5 |
6 | import inspect, sys
7 | import matplotlib.pyplot as plt
8 | from pathlib import Path
9 | from abc import ABCMeta, abstractmethod
10 |
11 | sys.path.append(str(Path(__file__).resolve().parent.parent))
12 | from utility import class_diagram, output_image
13 |
14 | class Cellphone(metaclass = ABCMeta):
15 | """
16 | Abstract base class with __init__ as the abstract method
17 | Used for inheritance by different types of Cellphones
18 |
19 | @return-values: name of cellphone
20 | """
21 |
22 | @abstractmethod
23 | def __init__(self):
24 | self._cname = None
25 | self._model = None
26 | self._android = None
27 | self._topfeatures = []
28 |
29 | def get_cellphonename(self):
30 | return self._cname + " " + self._model
31 |
32 | #Logging functions
33 | def prepare(self):
34 | print("Wiring...")
35 | print("Building...")
36 | print("Assembling...")
37 | print("Painting...")
38 |
39 | def test(self):
40 | print("Testing for regulations...")
41 |
42 |
43 | class SamsungGalaxyJ8(Cellphone):
44 | """
45 | Class used for customising the type of cellphone needed by client / provided by store to client
46 | Here we use the abstract method __init__ to set the cellphone attributes
47 |
48 | @params: class to inherit
49 | """
50 |
51 | def __init__(self):
52 | super(SamsungGalaxyJ8, self).__init__()
53 | self._cname = "Samsung"
54 | self._model = "Galaxy J8"
55 | self._android = "Android 8 Oreo"
56 | self._topfeatures.append("Snapdragon 450")
57 | self._topfeatures.append("Octacore 1.6")
58 | self._topfeatures.append("3500mAh battery")
59 | self._topfeatures.append("4GB Ram")
60 |
61 | class SamsungGalaxyA6(Cellphone):
62 | """
63 | Class used for customising the type of cellphone needed by client / provided by store to client
64 | Here we use the abstract method __init__ to set the cellphone attributes
65 |
66 | @params: class to inherit
67 | """
68 |
69 | def __init__(self):
70 | super(SamsungGalaxyA6, self).__init__()
71 | self._cname = "Samsung"
72 | self._model = "Galaxy A6"
73 | self._android = "Android 8 Oreo"
74 | self._topfeatures.append("Exynos 7870")
75 | self._topfeatures.append("Octacore 1.5")
76 | self._topfeatures.append("3200mAh battery")
77 | self._topfeatures.append("3GB Ram")
78 |
79 | class OppoF7(Cellphone):
80 | """
81 | Class used for customising the type of cellphone needed by client / provided by store to client
82 | Here we use the abstract method __init__ to set the cellphone attributes
83 |
84 | @params: class to inherit
85 | """
86 |
87 | def __init__(self):
88 | super(OppoF7, self).__init__()
89 | self._cname = "Oppo"
90 | self._model = "F7"
91 | self._android = "Android 8.1 Oreo"
92 | self._topfeatures.append("MediaTek MT6771")
93 | self._topfeatures.append("Octacore 2.0")
94 | self._topfeatures.append("3400mAh battery")
95 | self._topfeatures.append("4GB Ram")
96 |
97 | class OppoF5(Cellphone):
98 | """
99 | Class used for customising the type of cellphone needed by client / provided by store to client
100 | Here we use the abstract method __init__ to set the cellphone attributes
101 |
102 | @params: class to inherit
103 | """
104 |
105 | def __init__(self):
106 | super(OppoF5, self).__init__()
107 | self._cname = "Oppo"
108 | self._model = "F5"
109 | self._android = "Android 7 Nougat"
110 | self._topfeatures.append("MediaTek MT6763")
111 | self._topfeatures.append("Octacore 2.5")
112 | self._topfeatures.append("3200mAh battery")
113 | self._topfeatures.append("3GB Ram")
114 |
115 | class CellphoneFactory(metaclass = ABCMeta):
116 | """
117 | Abstract Interface for creating objects
118 | Here we do not instantiate the object but pass the instantiation to further subclasses
119 |
120 | @return-values: Complete cellphone delivered to client
121 | """
122 |
123 | @abstractmethod
124 | def create_cellphone(self, cell):
125 | pass
126 |
127 | def order_cellphone(self, c_type):
128 | cellphone = self.create_cellphone(c_type)
129 | print("---Serving order for: " + cellphone.get_cellphonename() + " ---")
130 | cellphone.prepare()
131 | cellphone.test()
132 | return cellphone
133 |
134 |
135 | class SamsungFactory(CellphoneFactory):
136 | """
137 | Subclass of the cellphone factory for instantiating appropriate samsung object
138 | Here we use the ideal concept of factorymethod design pattern by allowing the subclass to initialise the class
139 |
140 | @return-values: instance of samsung cellphone
141 | """
142 |
143 | def create_cellphone(self, c_type):
144 | if c_type == "J8":
145 | return SamsungGalaxyJ8()
146 | elif tesla_type == "A6":
147 | return SamsungGalaxyA6()
148 | else:
149 | return None
150 |
151 | class OppoFactory(CellphoneFactory):
152 | """
153 | Subclass of the cellphone factory for instantiating appropriate oppo object
154 | Here we use the ideal concept of factorymethod design pattern by allowing the subclass to initialise the class
155 |
156 | @return-values: instance of oppo cellphone
157 | """
158 |
159 | def create_cellphone(self, c_type):
160 | if c_type == "F7":
161 | return OppoF7()
162 | elif tesla_type == "F5":
163 | return OppoF5()
164 | else:
165 | return None
166 |
167 | def test_factory():
168 | """
169 | Demonstration of factorymethod pattern
170 | """
171 |
172 | samsungfactory = SamsungFactory()
173 | oppofactory = OppoFactory()
174 |
175 | c1 = samsungfactory.order_cellphone("J8")
176 | print("Ordered successfully: " + c1.get_cellphonename() + "\n")
177 |
178 | c2 = oppofactory.order_cellphone("F7")
179 | print("Ordered successfully: " + c2.get_cellphonename() + "\n")
180 |
181 | def get_code():
182 | """
183 | @return-values: source code
184 | """
185 |
186 | a = inspect.getsource(Cellphone)
187 | b = inspect.getsource(SamsungGalaxyJ8)
188 | c = inspect.getsource(SamsungGalaxyA6)
189 | d = inspect.getsource(OppoF7)
190 | e = inspect.getsource(OppoF5)
191 | f = inspect.getsource(SamsungFactory)
192 | g = inspect.getsource(OppoFactory)
193 | h = inspect.getsource(test_factory)
194 | return a + '\n' + b + '\n' + c + '\n' + d + '\n' + e + '\n' + f + '\n' + g + '\n' + h
195 |
196 | def get_classdiagram():
197 | """
198 | @return-values: matplotlib object with class diagram
199 | """
200 |
201 | diagram = class_diagram("factorymethod.png")
202 | plt.show()
203 | return diagram
204 |
205 | def get_outputimage():
206 | """
207 | @return-values: matplotlib object with code output
208 | """
209 |
210 | output = output_image("factorymethod_cellphone.png")
211 | plt.show()
212 | return output
--------------------------------------------------------------------------------
/pydesignpatterns/creational/simplefactory_pizza.py:
--------------------------------------------------------------------------------
1 | """
2 | Author: CHIRAG SHAH
3 | Created On: 14th July 2018
4 | """
5 |
6 | import inspect, sys
7 | import matplotlib.pyplot as plt
8 | from pathlib import Path
9 | from abc import ABCMeta, abstractmethod
10 |
11 | sys.path.append(str(Path(__file__).resolve().parent.parent))
12 | from utility import class_diagram, output_image
13 |
14 | class Pizza(metaclass = ABCMeta):
15 | """
16 | Abstract base class with __init__ as the abstract method
17 | Used for inheritance by different types of Pizzas
18 |
19 | @return-values: name of pizza
20 | """
21 |
22 | @abstractmethod
23 | def __init__(self):
24 | pass
25 |
26 | def get_pizzaname(self):
27 | return self._name
28 |
29 | #Logging functions
30 | def make(self):
31 | print("Preparing: "+ self._name)
32 |
33 | def bake(self):
34 | print("Baking: "+ self._name)
35 |
36 | def chop(self):
37 | print("Chopping into pieces: "+ self._name)
38 |
39 | def pack(self):
40 | print("Packing for delivery: "+ self._name)
41 |
42 |
43 | class DominoesPizzaFactory:
44 | """
45 | Factory interface class used for selecting type of pizza
46 | Here we use the ideal concept of factory design pattern by hiding the object creation logic from the client
47 |
48 | @return-values: instance of pizza type selected by user
49 | """
50 |
51 | @staticmethod
52 | def create_pizza(pizza_type):
53 | pizza = None
54 | if pizza_type == "margherita":
55 | pizza = MargheritaPizza()
56 |
57 | elif pizza_type == "peppypaneer":
58 | pizza = PeppyPaneerPizza()
59 |
60 | elif pizza_type == "cheeseburst":
61 | pizza = CheeseBurstPizza()
62 |
63 | elif pizza_type == "farmhouse":
64 | pizza = FarmHousePizza()
65 |
66 | elif pizza_type == "mexican":
67 | pizza = MexicanPizza()
68 |
69 | return pizza
70 |
71 | class MargheritaPizza(Pizza):
72 | """
73 | Class used for customising the type of pizza needed by client / provided by store to client
74 | Here we use the abstract method __init__ to set the pizza attributes
75 |
76 | @params: class to inherit
77 | """
78 |
79 | def __init__(self):
80 | self._name = "Margherita Pizza"
81 | self._dough = "Wheat Thin Crust"
82 | self._size = "Medium"
83 | self._sauce = "Tomato"
84 | self._toppings = []
85 | self._toppings.append("Fresh Mozzarella")
86 | self._toppings.append("Sliced Tomato")
87 | self._toppings.append("Sliced Black Olives")
88 |
89 | class PeppyPaneerPizza(Pizza):
90 | """
91 | Class used for customising the type of pizza needed by client / provided by store to client
92 | Here we use the abstract method __init__ to set the pizza attributes
93 |
94 | @params: class to inherit
95 | """
96 |
97 | def __init__(self):
98 | self._name = "Peppy Paneer"
99 | self._dough = "Classic Hand Tossed"
100 | self._size = "Small"
101 | self._sauce = "Marinara"
102 | self._toppings = []
103 | self._toppings.append("Sliced Paneer")
104 | self._toppings.append("Sliced Onion")
105 | self._toppings.append("Sliced Pepperoni")
106 |
107 | class CheeseBurstPizza(Pizza):
108 | """
109 | Class used for customising the type of pizza needed by client / provided by store to client
110 | Here we use the abstract method __init__ to set the pizza attributes
111 |
112 | @params: class to inherit
113 | """
114 |
115 | def __init__(self):
116 | self._name = "Cheese Burst"
117 | self._dough = "Pan Pizza"
118 | self._size = "Medium"
119 | self._sauce = "Tomato"
120 | self._toppings = []
121 | self._toppings.append("Sliced Corns")
122 | self._toppings.append("Roasted Red Pepper")
123 | self._toppings.append("Sliced Broccoli")
124 |
125 | class FarmHousePizza(Pizza):
126 | """
127 | Class used for customising the type of pizza needed by client / provided by store to client
128 | Here we use the abstract method __init__ to set the pizza attributes
129 |
130 | @params: class to inherit
131 | """
132 |
133 | def __init__(self):
134 | self._name = "Farm House"
135 | self._dough = "Thick Crust"
136 | self._size = "Large"
137 | self._sauce = "Marinara"
138 | self._toppings = []
139 | self._toppings.append("Sliced Onions")
140 | self._toppings.append("Sliced Capsicum")
141 | self._toppings.append("Sliced Garlic")
142 | self._toppings.append("Fresh Mushrooms")
143 | self._toppings.append("Jalapeno Peppers")
144 | self._toppings.append("Fresh Pineapple")
145 |
146 | class MexicanPizza(Pizza):
147 | """
148 | Class used for customising the type of pizza needed by client / provided by store to client
149 | Here we use the abstract method __init__ to set the pizza attributes
150 |
151 | @params: class to inherit
152 | """
153 |
154 | def __init__(self):
155 | self._name = "Mexican"
156 | self._dough = "Classic Hand Tossed"
157 | self._size = "Small"
158 | self._sauce = "Mexican"
159 | self._toppings = []
160 | self._toppings.append("Sliced Zucchini")
161 | self._toppings.append("Caramalised Onions")
162 | self._toppings.append("Roasted Garlic")
163 |
164 |
165 | class DominoesPizzaStore:
166 | """
167 | Class which interacts with the client to order his pizza
168 | Here we initialise the factory class which serves the functionality of creating instances
169 |
170 | @return-values: Complete pizza delivered to client
171 | """
172 |
173 | def __init__(self, factory):
174 | self._factory = factory
175 |
176 | def order_pizza(self, pizza_type= None):
177 | if pizza_type is None:
178 | pizza_type = "farmhouse"
179 |
180 | pizza = DominoesPizzaFactory.create_pizza(pizza_type)
181 | pizza.make()
182 | pizza.bake()
183 | pizza.chop()
184 | pizza.pack()
185 | return pizza
186 |
187 |
188 | def test_factory():
189 | """
190 | Demonstration of factory pattern
191 | """
192 |
193 | factory = DominoesPizzaFactory()
194 | store = DominoesPizzaStore(factory)
195 | pizza = store.order_pizza()
196 | print("Ordered: " + pizza.get_pizzaname())
197 |
198 | def get_code():
199 | """
200 | @return-values: source code
201 | """
202 |
203 | a = inspect.getsource(Pizza)
204 | b = inspect.getsource(DominoesPizzaFactory)
205 | c = inspect.getsource(MargheritaPizza)
206 | d = inspect.getsource(PeppyPaneerPizza)
207 | e = inspect.getsource(CheeseBurstPizza)
208 | f = inspect.getsource(FarmHousePizza)
209 | g = inspect.getsource(MexicanPizza)
210 | h = inspect.getsource(DominoesPizzaStore)
211 | i = inspect.getsource(test_factory)
212 | return a + '\n' + b + '\n' + c + '\n' + d + '\n' + e + '\n' + f + '\n' + g + '\n' + h + '\n' + i
213 |
214 | def get_classdiagram():
215 | """
216 | @return-values: matplotlib object with class diagram
217 | """
218 |
219 | diagram = class_diagram("simplefactory.png")
220 | #plt.show()
221 | return diagram
222 |
223 | def get_outputimage():
224 | """
225 | @return-values: matplotlib object with code output
226 | """
227 |
228 | output = output_image("simplefactory_pizza.png")
229 | #plt.show()
230 | return output
--------------------------------------------------------------------------------
/pydesignpatterns/creational/factorymethod_car.py:
--------------------------------------------------------------------------------
1 | """
2 | Author: CHIRAG SHAH
3 | Created On: 17th July 2018
4 | """
5 |
6 | import inspect, sys
7 | import matplotlib.pyplot as plt
8 | from pathlib import Path
9 | from abc import ABCMeta, abstractmethod
10 |
11 | sys.path.append(str(Path(__file__).resolve().parent.parent))
12 | from utility import class_diagram, output_image
13 |
14 | class Car(metaclass = ABCMeta):
15 | """
16 | Abstract base class with __init__ as the abstract method
17 | Used for inheritance by different types of Cars
18 |
19 | @return-values: name of car
20 | """
21 |
22 | @abstractmethod
23 | def __init__(self):
24 | self._cname = None
25 | self._model = None
26 | self._type = None
27 | self._topfeatures = []
28 |
29 | def get_carname(self):
30 | return self._cname + " " + self._model
31 |
32 | #Logging functions
33 | def blueprint(self):
34 | print("Creating blueprint...")
35 |
36 | def prepare(self):
37 | print("Wielding...")
38 | print("Drilling...")
39 | print("Wiring...")
40 | print("Building...")
41 | print("Assembling...")
42 | print("Painting...")
43 |
44 | def test(self):
45 | print("Testing for regulations...")
46 |
47 |
48 | class TeslaX(Car):
49 | """
50 | Class used for customising the type of car needed by client / provided by store to client
51 | Here we use the abstract method __init__ to set the car attributes
52 |
53 | @params: class to inherit
54 | """
55 |
56 | def __init__(self):
57 | super(TeslaX, self).__init__()
58 | self._cname = "Tesla"
59 | self._model = "Model X"
60 | self._type = "Electric"
61 | self._topfeatures.append("outrageous acceleration")
62 | self._topfeatures.append("sleek design")
63 | self._topfeatures.append("zero emission driving")
64 | self._topfeatures.append("falcon wings")
65 | self._topfeatures.append("auto-summon")
66 |
67 | class TeslaS(Car):
68 | """
69 | Class used for customising the type of car needed by client / provided by store to client
70 | Here we use the abstract method __init__ to set the car attributes
71 |
72 | @params: class to inherit
73 | """
74 |
75 | def __init__(self):
76 | super(TeslaS, self).__init__()
77 | self._cname = "Tesla"
78 | self._model = "Model S"
79 | self._type = "Electric"
80 | self._topfeatures.append("flush door handles")
81 | self._topfeatures.append("glass cockpit")
82 | self._topfeatures.append("zero emission driving")
83 | self._topfeatures.append("active cruise control")
84 | self._topfeatures.append("outrageous acceleration")
85 |
86 | class Tesla3(Car):
87 | """
88 | Class used for customising the type of car needed by client / provided by store to client
89 | Here we use the abstract method __init__ to set the car attributes
90 |
91 | @params: class to inherit
92 | """
93 |
94 | def __init__(self):
95 | super(Tesla3, self).__init__()
96 | self._cname = "Tesla"
97 | self._model = "Model 3"
98 | self._type = "Electric"
99 | self._topfeatures.append("super charging")
100 | self._topfeatures.append("large cargo capacity")
101 | self._topfeatures.append("HOA access")
102 | self._topfeatures.append("latch attachments")
103 | self._topfeatures.append("aerodynamic")
104 |
105 | class BMWi3s(Car):
106 | """
107 | Class used for customising the type of car needed by client / provided by store to client
108 | Here we use the abstract method __init__ to set the car attributes
109 |
110 | @params: class to inherit
111 | """
112 |
113 | def __init__(self):
114 | super(BMWi3s, self).__init__()
115 | self._cname = "BMW"
116 | self._model = "i3s"
117 | self._type = "Electric"
118 | self._topfeatures.append("strong horsepower")
119 | self._topfeatures.append("sports suspension")
120 | self._topfeatures.append("hardcore metal plating")
121 | self._topfeatures.append("DA systems")
122 | self._topfeatures.append("all led lighting")
123 |
124 | class BMW7(Car):
125 | """
126 | Class used for customising the type of car needed by client / provided by store to client
127 | Here we use the abstract method __init__ to set the car attributes
128 |
129 | @params: class to inherit
130 | """
131 |
132 | def __init__(self):
133 | super(BMW7, self).__init__()
134 | self._cname = "BMW"
135 | self._model = "7i"
136 | self._type = "Non-Electric"
137 | self._topfeatures.append("hand gestures")
138 | self._topfeatures.append("auto park")
139 | self._topfeatures.append("extremely lightweight")
140 | self._topfeatures.append("efficient auto system planning")
141 | self._topfeatures.append("side impact beams")
142 |
143 |
144 | class CarFactory(metaclass = ABCMeta):
145 | """
146 | Abstract Interface for creating objects
147 | Here we do not instantiate the object but pass the instantiation to further subclasses
148 |
149 | @return-values: Complete car delivered to client
150 | """
151 |
152 | @abstractmethod
153 | def create_car(self, car):
154 | pass
155 |
156 | def order_car(self, car_type):
157 | car = self.create_car(car_type)
158 | print("---Serving order for: " + car.get_carname() + " ---")
159 | car.blueprint()
160 | car.prepare()
161 | car.test()
162 | return car
163 |
164 |
165 | class TeslaFactory(CarFactory):
166 | """
167 | Subclass of the car factory for instantiating appropriate tesla object
168 | Here we use the ideal concept of factorymethod design pattern by allowing the subclass to initialise the class
169 |
170 | @return-values: instance of tesla car
171 | """
172 |
173 | def create_car(self, tesla_type):
174 | if tesla_type == "tesla x":
175 | return TeslaX()
176 | elif tesla_type == "tesla s":
177 | return TeslaS()
178 | elif tesla_type == "tesla 3":
179 | return Tesla3()
180 | else:
181 | return None
182 |
183 |
184 | class BMWFactory(CarFactory):
185 | """
186 | Subclass of the car factory for instantiating appropriate bmw object
187 | Here we use the ideal concept of factorymethod design pattern by allowing the subclass to initialise the class
188 |
189 | @return-values: instance of bmw car
190 | """
191 |
192 | def create_car(self, bmw_type):
193 | if bmw_type == "bmw i3s":
194 | return BMWi3s()
195 | elif bmw_type == "bmw 7":
196 | return BMW7()
197 | else:
198 | return None
199 |
200 | def test_factory():
201 | """
202 | Demonstration of factorymethod pattern
203 | """
204 |
205 | teslafactory = TeslaFactory()
206 | bmwfactory = BMWFactory()
207 |
208 | car1 = teslafactory.order_car("tesla x")
209 | print("Ordered successfully: " + car1.get_carname() + "\n")
210 |
211 | car2 = bmwfactory.order_car("bmw i3s")
212 | print("Ordered successfully: " + car2.get_carname() + "\n")
213 |
214 | def get_code():
215 | """
216 | @return-values: source code
217 | """
218 |
219 | a = inspect.getsource(Car)
220 | b = inspect.getsource(TeslaX)
221 | c = inspect.getsource(TeslaS)
222 | d = inspect.getsource(Tesla3)
223 | e = inspect.getsource(BMWi3s)
224 | f = inspect.getsource(BMW7)
225 | g = inspect.getsource(CarFactory)
226 | h = inspect.getsource(TeslaFactory)
227 | i = inspect.getsource(BMWFactory)
228 | j = inspect.getsource(test_factory)
229 | return a + '\n' + b + '\n' + c + '\n' + d + '\n' + e + '\n' + f + '\n' + g + '\n' + h + '\n' + i + '\n' + j
230 |
231 | def get_classdiagram():
232 | """
233 | @return-values: matplotlib object with class diagram
234 | """
235 |
236 | diagram = class_diagram("factorymethod.png")
237 | #plt.show()
238 | return diagram
239 |
240 | def get_outputimage():
241 | """
242 | @return-values: matplotlib object with code output
243 | """
244 |
245 | output = output_image("factorymethod_car.png")
246 | #plt.show()
247 | return output
--------------------------------------------------------------------------------
/tests/test_factory.py:
--------------------------------------------------------------------------------
1 | """
2 | Author: CHIRAG SHAH
3 | Created On: 15th July 2018
4 | Modified On: 23th July 2018
5 | """
6 |
7 | import unittest, sys, inspect
8 | from pathlib import Path
9 | from abc import ABCMeta
10 |
11 |
12 | ROOT_DIR = str(Path(__file__).resolve().parent.parent)
13 | sys.path.append(ROOT_DIR)
14 |
15 | from pydesignpatterns.creational import (
16 | simplefactory_naive,
17 | simplefactory_pizza,
18 | simplefactory_burger,
19 | factorymethod_naive,
20 | factorymethod_car,
21 | factorymethod_cellphone,
22 | abstractfactory_shape,
23 | abstractfactory_naive
24 | )
25 |
26 | class TestFactory(unittest.TestCase):
27 |
28 | def test_classes(self):
29 | self.assertEqual(inspect.isclass(simplefactory_naive.AbstractProduct), True)
30 | self.assertEqual(inspect.isclass(simplefactory_naive.ProductFactory), True)
31 | self.assertEqual(inspect.isclass(simplefactory_naive.Product1), True)
32 | self.assertEqual(inspect.isclass(simplefactory_naive.Product2), True)
33 | self.assertEqual(inspect.isclass(simplefactory_naive.Client), True)
34 |
35 | def test_instances(self):
36 | self.assertEqual(isinstance(simplefactory_naive.AbstractProduct, ABCMeta), True)
37 | self.assertEqual(isinstance(simplefactory_naive.Product1(), simplefactory_naive.AbstractProduct), True)
38 | self.assertEqual(isinstance(simplefactory_naive.Product2(), simplefactory_naive.AbstractProduct), True)
39 |
40 | def test_orderedproduct(self):
41 | factory = simplefactory_naive.ProductFactory()
42 | store = simplefactory_naive.Client(factory)
43 |
44 | product = store.order_product("product 1")
45 | self.assertEqual(product.get_product(), "I am Product A")
46 |
47 | product = store.order_product("product 2")
48 | self.assertEqual(product.get_product(), "I am Product B")
49 |
50 | product = store.order_product()
51 | self.assertEqual(product.get_product(), "I am Product B")
52 |
53 | class TestFactoryPizza(unittest.TestCase):
54 |
55 | def test_classes(self):
56 | self.assertEqual(inspect.isclass(simplefactory_pizza.Pizza), True)
57 | self.assertEqual(inspect.isclass(simplefactory_pizza.DominoesPizzaFactory), True)
58 | self.assertEqual(inspect.isclass(simplefactory_pizza.MargheritaPizza), True)
59 | self.assertEqual(inspect.isclass(simplefactory_pizza.PeppyPaneerPizza), True)
60 | self.assertEqual(inspect.isclass(simplefactory_pizza.CheeseBurstPizza), True)
61 | self.assertEqual(inspect.isclass(simplefactory_pizza.FarmHousePizza), True)
62 | self.assertEqual(inspect.isclass(simplefactory_pizza.MexicanPizza), True)
63 | self.assertEqual(inspect.isclass(simplefactory_pizza.DominoesPizzaStore), True)
64 |
65 | def test_instances(self):
66 | self.assertEqual(isinstance(simplefactory_pizza.Pizza, ABCMeta), True)
67 | self.assertEqual(isinstance(simplefactory_pizza.MargheritaPizza(), simplefactory_pizza.Pizza), True)
68 | self.assertEqual(isinstance(simplefactory_pizza.PeppyPaneerPizza(), simplefactory_pizza.Pizza), True)
69 | self.assertEqual(isinstance(simplefactory_pizza.CheeseBurstPizza(), simplefactory_pizza.Pizza), True)
70 | self.assertEqual(isinstance(simplefactory_pizza.FarmHousePizza(), simplefactory_pizza.Pizza), True)
71 | self.assertEqual(isinstance(simplefactory_pizza.MexicanPizza(), simplefactory_pizza.Pizza), True)
72 |
73 | def test_orderedpizza(self):
74 | factory = simplefactory_pizza.DominoesPizzaFactory()
75 | store = simplefactory_pizza.DominoesPizzaStore(factory)
76 |
77 | pizza = store.order_pizza("cheeseburst")
78 | self.assertEqual(pizza.get_pizzaname(), "Cheese Burst")
79 |
80 | pizza = store.order_pizza("mexican")
81 | self.assertEqual(pizza.get_pizzaname(), "Mexican")
82 |
83 | pizza = store.order_pizza()
84 | self.assertEqual(pizza.get_pizzaname(), "Farm House")
85 |
86 |
87 | class TestFactoryBurger(unittest.TestCase):
88 |
89 | def test_classes(self):
90 | self.assertEqual(inspect.isclass(simplefactory_burger.Burger), True)
91 | self.assertEqual(inspect.isclass(simplefactory_burger.BurgerFactory), True)
92 | self.assertEqual(inspect.isclass(simplefactory_burger.GrilledMushroomBurger), True)
93 | self.assertEqual(inspect.isclass(simplefactory_burger.MixVeggieBurger), True)
94 | self.assertEqual(inspect.isclass(simplefactory_burger.CaramalizedOnionBurger), True)
95 | self.assertEqual(inspect.isclass(simplefactory_burger.CheeseBurger), True)
96 | self.assertEqual(inspect.isclass(simplefactory_burger.BurgerStore), True)
97 |
98 | def test_instances(self):
99 | self.assertEqual(isinstance(simplefactory_burger.Burger, ABCMeta), True)
100 | self.assertEqual(isinstance(simplefactory_burger.MixVeggieBurger(), simplefactory_burger.Burger), True)
101 | self.assertEqual(isinstance(simplefactory_burger.GrilledMushroomBurger(), simplefactory_burger.Burger), True)
102 | self.assertEqual(isinstance(simplefactory_burger.CaramalizedOnionBurger(), simplefactory_burger.Burger), True)
103 | self.assertEqual(isinstance(simplefactory_burger.CheeseBurger(), simplefactory_burger.Burger), True)
104 |
105 | def test_orderedburger(self):
106 | factory = simplefactory_burger.BurgerFactory()
107 | store = simplefactory_burger.BurgerStore(factory)
108 |
109 | burger = store.order_burger("mixveggie")
110 | self.assertEqual(burger.get_burgername(), "Mix Veggie")
111 |
112 | burger = store.order_burger("grilledmushroom")
113 | self.assertEqual(burger.get_burgername(), "Grilled Mushroom")
114 |
115 | burger = store.order_burger()
116 | self.assertEqual(burger.get_burgername(), "Mix Veggie")
117 |
118 | class TestFactoryMethodNaive(unittest.TestCase):
119 | def test_classes(self):
120 | self.assertEqual(inspect.isclass(factorymethod_naive.AbstractCreator), True)
121 | self.assertEqual(inspect.isclass(factorymethod_naive.ConcreteCreatorA), True)
122 | self.assertEqual(inspect.isclass(factorymethod_naive.ConcreteCreatorB), True)
123 | self.assertEqual(inspect.isclass(factorymethod_naive.AbstractProduct), True)
124 | self.assertEqual(inspect.isclass(factorymethod_naive.ConcreteProductA), True)
125 | self.assertEqual(inspect.isclass(factorymethod_naive.ConcreteProductB), True)
126 |
127 | def test_instances(self):
128 | self.assertEqual(isinstance(factorymethod_naive.AbstractCreator, ABCMeta), True)
129 | self.assertEqual(isinstance(factorymethod_naive.ConcreteCreatorA(), factorymethod_naive.AbstractCreator), True)
130 | self.assertEqual(isinstance(factorymethod_naive.ConcreteCreatorB(), factorymethod_naive.AbstractCreator), True)
131 | self.assertEqual(isinstance(factorymethod_naive.AbstractProduct, ABCMeta), True)
132 | self.assertEqual(isinstance(factorymethod_naive.ConcreteProductA(), factorymethod_naive.AbstractProduct), True)
133 | self.assertEqual(isinstance(factorymethod_naive.ConcreteProductB(), factorymethod_naive.AbstractProduct), True)
134 |
135 | def test_factorymethod(self):
136 |
137 | concretecreator = factorymethod_naive.ConcreteCreatorA()
138 | self.assertEqual(concretecreator.product.interface(), "I am in A")
139 |
140 | class TestFactoryMethodCar(unittest.TestCase):
141 |
142 | def test_classes(self):
143 | self.assertEqual(inspect.isclass(factorymethod_car.Car), True)
144 | self.assertEqual(inspect.isclass(factorymethod_car.TeslaX), True)
145 | self.assertEqual(inspect.isclass(factorymethod_car.TeslaS), True)
146 | self.assertEqual(inspect.isclass(factorymethod_car.Tesla3), True)
147 | self.assertEqual(inspect.isclass(factorymethod_car.BMWi3s), True)
148 | self.assertEqual(inspect.isclass(factorymethod_car.BMW7), True)
149 | self.assertEqual(inspect.isclass(factorymethod_car.CarFactory), True)
150 | self.assertEqual(inspect.isclass(factorymethod_car.TeslaFactory), True)
151 | self.assertEqual(inspect.isclass(factorymethod_car.BMWFactory), True)
152 |
153 | def test_instances(self):
154 | self.assertEqual(isinstance(factorymethod_car.Car, ABCMeta), True)
155 | self.assertEqual(isinstance(factorymethod_car.TeslaX(), factorymethod_car.Car), True)
156 | self.assertEqual(isinstance(factorymethod_car.TeslaS(), factorymethod_car.Car), True)
157 | self.assertEqual(isinstance(factorymethod_car.Tesla3(), factorymethod_car.Car), True)
158 | self.assertEqual(isinstance(factorymethod_car.BMWi3s(), factorymethod_car.Car), True)
159 | self.assertEqual(isinstance(factorymethod_car.BMW7(), factorymethod_car.Car), True)
160 | self.assertEqual(isinstance(factorymethod_car.CarFactory, ABCMeta), True)
161 | self.assertEqual(isinstance(factorymethod_car.TeslaFactory(), factorymethod_car.CarFactory), True)
162 | self.assertEqual(isinstance(factorymethod_car.BMWFactory(), factorymethod_car.CarFactory), True)
163 |
164 | def test_orderedcar(self):
165 | teslafactory = factorymethod_car.TeslaFactory()
166 | bmwfactory = factorymethod_car.BMWFactory()
167 |
168 | car1 = teslafactory.order_car("tesla x")
169 | self.assertEqual(car1.get_carname(), "Tesla Model X")
170 |
171 | car2 = bmwfactory.order_car("bmw i3s")
172 | self.assertEqual(car2.get_carname(), "BMW i3s")
173 |
174 | class TestFactoryMethodCellphone(unittest.TestCase):
175 |
176 | def test_classes(self):
177 | self.assertEqual(inspect.isclass(factorymethod_cellphone.Cellphone), True)
178 | self.assertEqual(inspect.isclass(factorymethod_cellphone.SamsungGalaxyJ8), True)
179 | self.assertEqual(inspect.isclass(factorymethod_cellphone.SamsungGalaxyA6), True)
180 | self.assertEqual(inspect.isclass(factorymethod_cellphone.OppoF7), True)
181 | self.assertEqual(inspect.isclass(factorymethod_cellphone.OppoF5), True)
182 | self.assertEqual(inspect.isclass(factorymethod_cellphone.CellphoneFactory), True)
183 | self.assertEqual(inspect.isclass(factorymethod_cellphone.SamsungFactory), True)
184 | self.assertEqual(inspect.isclass(factorymethod_cellphone.OppoFactory), True)
185 |
186 | def test_instances(self):
187 | self.assertEqual(isinstance(factorymethod_cellphone.Cellphone, ABCMeta), True)
188 | self.assertEqual(isinstance(factorymethod_cellphone.SamsungGalaxyJ8(), factorymethod_cellphone.Cellphone), True)
189 | self.assertEqual(isinstance(factorymethod_cellphone.SamsungGalaxyA6(), factorymethod_cellphone.Cellphone), True)
190 | self.assertEqual(isinstance(factorymethod_cellphone.OppoF7(), factorymethod_cellphone.Cellphone), True)
191 | self.assertEqual(isinstance(factorymethod_cellphone.OppoF5(), factorymethod_cellphone.Cellphone), True)
192 | self.assertEqual(isinstance(factorymethod_cellphone.CellphoneFactory, ABCMeta), True)
193 | self.assertEqual(isinstance(factorymethod_cellphone.SamsungFactory(), factorymethod_cellphone.CellphoneFactory), True)
194 | self.assertEqual(isinstance(factorymethod_cellphone.OppoFactory(), factorymethod_cellphone.CellphoneFactory), True)
195 |
196 | def test_orderedcellphone(self):
197 | samsungfactory = factorymethod_cellphone.SamsungFactory()
198 | c1 = samsungfactory.order_cellphone("J8")
199 | self.assertEqual(c1.get_cellphonename(), "Samsung Galaxy J8")
200 |
201 | class TestAbstractFactoryShape(unittest.TestCase):
202 |
203 | def test_classes(self):
204 | self.assertEqual(inspect.isclass(abstractfactory_shape.DrawFactory), True)
205 | self.assertEqual(inspect.isclass(abstractfactory_shape.CircleFactory), True)
206 | self.assertEqual(inspect.isclass(abstractfactory_shape.TriangleFactory), True)
207 | self.assertEqual(inspect.isclass(abstractfactory_shape.CreateShape), True)
208 | self.assertEqual(inspect.isclass(abstractfactory_shape.FillShape), True)
209 | self.assertEqual(inspect.isclass(abstractfactory_shape.CircleShape), True)
210 | self.assertEqual(inspect.isclass(abstractfactory_shape.CircleColor), True)
211 | self.assertEqual(inspect.isclass(abstractfactory_shape.TriangleShape), True)
212 | self.assertEqual(inspect.isclass(abstractfactory_shape.TriangleColor), True)
213 | self.assertEqual(inspect.isclass(abstractfactory_shape.ShapeFactoryStore), True)
214 |
215 | def test_instances(self):
216 | self.assertEqual(isinstance(abstractfactory_shape.DrawFactory, ABCMeta), True)
217 | self.assertEqual(isinstance(abstractfactory_shape.CircleFactory(), abstractfactory_shape.DrawFactory), True)
218 | self.assertEqual(isinstance(abstractfactory_shape.TriangleFactory(), abstractfactory_shape.DrawFactory), True)
219 | self.assertEqual(isinstance(abstractfactory_shape.CreateShape, ABCMeta), True)
220 | self.assertEqual(isinstance(abstractfactory_shape.FillShape, ABCMeta), True)
221 | self.assertEqual(isinstance(abstractfactory_shape.CircleShape(), abstractfactory_shape.CreateShape), True)
222 | self.assertEqual(isinstance(abstractfactory_shape.CircleColor(), abstractfactory_shape.FillShape), True)
223 | self.assertEqual(isinstance(abstractfactory_shape.TriangleShape(), abstractfactory_shape.CreateShape), True)
224 | self.assertEqual(isinstance(abstractfactory_shape.TriangleColor(), abstractfactory_shape.FillShape), True)
225 |
226 | class TestAbstractFactoryNaiveShape(unittest.TestCase):
227 |
228 | def test_classes(self):
229 | self.assertEqual(inspect.isclass(abstractfactory_naive.AbstractFactory), True)
230 | self.assertEqual(inspect.isclass(abstractfactory_naive.ConcreteFactory1), True)
231 | self.assertEqual(inspect.isclass(abstractfactory_naive.ConcreteFactory2), True)
232 | self.assertEqual(inspect.isclass(abstractfactory_naive.AbstractProductA), True)
233 | self.assertEqual(inspect.isclass(abstractfactory_naive.AbstractProductB), True)
234 | self.assertEqual(inspect.isclass(abstractfactory_naive.ConcreteProductA1), True)
235 | self.assertEqual(inspect.isclass(abstractfactory_naive.ConcreteProductA2), True)
236 | self.assertEqual(inspect.isclass(abstractfactory_naive.ConcreteProductB1), True)
237 | self.assertEqual(inspect.isclass(abstractfactory_naive.ConcreteProductB2), True)
238 |
239 | def test_instances(self):
240 | self.assertEqual(isinstance(abstractfactory_naive.AbstractFactory, ABCMeta), True)
241 | self.assertEqual(isinstance(abstractfactory_naive.ConcreteFactory1(), abstractfactory_naive.AbstractFactory), True)
242 | self.assertEqual(isinstance(abstractfactory_naive.ConcreteFactory2(), abstractfactory_naive.AbstractFactory), True)
243 | self.assertEqual(isinstance(abstractfactory_naive.AbstractProductA, ABCMeta), True)
244 | self.assertEqual(isinstance(abstractfactory_naive.AbstractProductB, ABCMeta), True)
245 | self.assertEqual(isinstance(abstractfactory_naive.ConcreteProductA1(), abstractfactory_naive.AbstractProductA), True)
246 | self.assertEqual(isinstance(abstractfactory_naive.ConcreteProductA2(), abstractfactory_naive.AbstractProductA), True)
247 | self.assertEqual(isinstance(abstractfactory_naive.ConcreteProductB1(), abstractfactory_naive.AbstractProductB), True)
248 | self.assertEqual(isinstance(abstractfactory_naive.ConcreteProductB2(), abstractfactory_naive.AbstractProductB), True)
249 |
250 | def test_factory(self):
251 | factory = abstractfactory_naive.ConcreteFactory1()
252 | p_a = factory.create_product_a()
253 | self.assertEqual(p_a.interface_a(), "I am in A1")
--------------------------------------------------------------------------------
/LICENSE:
--------------------------------------------------------------------------------
1 | GNU GENERAL PUBLIC LICENSE
2 | Version 3, 29 June 2007
3 |
4 | Copyright (C) 2007 Free Software Foundation, Inc.
5 | Everyone is permitted to copy and distribute verbatim copies
6 | of this license document, but changing it is not allowed.
7 |
8 | Preamble
9 |
10 | The GNU General Public License is a free, copyleft license for
11 | software and other kinds of works.
12 |
13 | The licenses for most software and other practical works are designed
14 | to take away your freedom to share and change the works. By contrast,
15 | the GNU General Public License is intended to guarantee your freedom to
16 | share and change all versions of a program--to make sure it remains free
17 | software for all its users. We, the Free Software Foundation, use the
18 | GNU General Public License for most of our software; it applies also to
19 | any other work released this way by its authors. You can apply it to
20 | your programs, too.
21 |
22 | When we speak of free software, we are referring to freedom, not
23 | price. Our General Public Licenses are designed to make sure that you
24 | have the freedom to distribute copies of free software (and charge for
25 | them if you wish), that you receive source code or can get it if you
26 | want it, that you can change the software or use pieces of it in new
27 | free programs, and that you know you can do these things.
28 |
29 | To protect your rights, we need to prevent others from denying you
30 | these rights or asking you to surrender the rights. Therefore, you have
31 | certain responsibilities if you distribute copies of the software, or if
32 | you modify it: responsibilities to respect the freedom of others.
33 |
34 | For example, if you distribute copies of such a program, whether
35 | gratis or for a fee, you must pass on to the recipients the same
36 | freedoms that you received. You must make sure that they, too, receive
37 | or can get the source code. And you must show them these terms so they
38 | know their rights.
39 |
40 | Developers that use the GNU GPL protect your rights with two steps:
41 | (1) assert copyright on the software, and (2) offer you this License
42 | giving you legal permission to copy, distribute and/or modify it.
43 |
44 | For the developers' and authors' protection, the GPL clearly explains
45 | that there is no warranty for this free software. For both users' and
46 | authors' sake, the GPL requires that modified versions be marked as
47 | changed, so that their problems will not be attributed erroneously to
48 | authors of previous versions.
49 |
50 | Some devices are designed to deny users access to install or run
51 | modified versions of the software inside them, although the manufacturer
52 | can do so. This is fundamentally incompatible with the aim of
53 | protecting users' freedom to change the software. The systematic
54 | pattern of such abuse occurs in the area of products for individuals to
55 | use, which is precisely where it is most unacceptable. Therefore, we
56 | have designed this version of the GPL to prohibit the practice for those
57 | products. If such problems arise substantially in other domains, we
58 | stand ready to extend this provision to those domains in future versions
59 | of the GPL, as needed to protect the freedom of users.
60 |
61 | Finally, every program is threatened constantly by software patents.
62 | States should not allow patents to restrict development and use of
63 | software on general-purpose computers, but in those that do, we wish to
64 | avoid the special danger that patents applied to a free program could
65 | make it effectively proprietary. To prevent this, the GPL assures that
66 | patents cannot be used to render the program non-free.
67 |
68 | The precise terms and conditions for copying, distribution and
69 | modification follow.
70 |
71 | TERMS AND CONDITIONS
72 |
73 | 0. Definitions.
74 |
75 | "This License" refers to version 3 of the GNU General Public License.
76 |
77 | "Copyright" also means copyright-like laws that apply to other kinds of
78 | works, such as semiconductor masks.
79 |
80 | "The Program" refers to any copyrightable work licensed under this
81 | License. Each licensee is addressed as "you". "Licensees" and
82 | "recipients" may be individuals or organizations.
83 |
84 | To "modify" a work means to copy from or adapt all or part of the work
85 | in a fashion requiring copyright permission, other than the making of an
86 | exact copy. The resulting work is called a "modified version" of the
87 | earlier work or a work "based on" the earlier work.
88 |
89 | A "covered work" means either the unmodified Program or a work based
90 | on the Program.
91 |
92 | To "propagate" a work means to do anything with it that, without
93 | permission, would make you directly or secondarily liable for
94 | infringement under applicable copyright law, except executing it on a
95 | computer or modifying a private copy. Propagation includes copying,
96 | distribution (with or without modification), making available to the
97 | public, and in some countries other activities as well.
98 |
99 | To "convey" a work means any kind of propagation that enables other
100 | parties to make or receive copies. Mere interaction with a user through
101 | a computer network, with no transfer of a copy, is not conveying.
102 |
103 | An interactive user interface displays "Appropriate Legal Notices"
104 | to the extent that it includes a convenient and prominently visible
105 | feature that (1) displays an appropriate copyright notice, and (2)
106 | tells the user that there is no warranty for the work (except to the
107 | extent that warranties are provided), that licensees may convey the
108 | work under this License, and how to view a copy of this License. If
109 | the interface presents a list of user commands or options, such as a
110 | menu, a prominent item in the list meets this criterion.
111 |
112 | 1. Source Code.
113 |
114 | The "source code" for a work means the preferred form of the work
115 | for making modifications to it. "Object code" means any non-source
116 | form of a work.
117 |
118 | A "Standard Interface" means an interface that either is an official
119 | standard defined by a recognized standards body, or, in the case of
120 | interfaces specified for a particular programming language, one that
121 | is widely used among developers working in that language.
122 |
123 | The "System Libraries" of an executable work include anything, other
124 | than the work as a whole, that (a) is included in the normal form of
125 | packaging a Major Component, but which is not part of that Major
126 | Component, and (b) serves only to enable use of the work with that
127 | Major Component, or to implement a Standard Interface for which an
128 | implementation is available to the public in source code form. A
129 | "Major Component", in this context, means a major essential component
130 | (kernel, window system, and so on) of the specific operating system
131 | (if any) on which the executable work runs, or a compiler used to
132 | produce the work, or an object code interpreter used to run it.
133 |
134 | The "Corresponding Source" for a work in object code form means all
135 | the source code needed to generate, install, and (for an executable
136 | work) run the object code and to modify the work, including scripts to
137 | control those activities. However, it does not include the work's
138 | System Libraries, or general-purpose tools or generally available free
139 | programs which are used unmodified in performing those activities but
140 | which are not part of the work. For example, Corresponding Source
141 | includes interface definition files associated with source files for
142 | the work, and the source code for shared libraries and dynamically
143 | linked subprograms that the work is specifically designed to require,
144 | such as by intimate data communication or control flow between those
145 | subprograms and other parts of the work.
146 |
147 | The Corresponding Source need not include anything that users
148 | can regenerate automatically from other parts of the Corresponding
149 | Source.
150 |
151 | The Corresponding Source for a work in source code form is that
152 | same work.
153 |
154 | 2. Basic Permissions.
155 |
156 | All rights granted under this License are granted for the term of
157 | copyright on the Program, and are irrevocable provided the stated
158 | conditions are met. This License explicitly affirms your unlimited
159 | permission to run the unmodified Program. The output from running a
160 | covered work is covered by this License only if the output, given its
161 | content, constitutes a covered work. This License acknowledges your
162 | rights of fair use or other equivalent, as provided by copyright law.
163 |
164 | You may make, run and propagate covered works that you do not
165 | convey, without conditions so long as your license otherwise remains
166 | in force. You may convey covered works to others for the sole purpose
167 | of having them make modifications exclusively for you, or provide you
168 | with facilities for running those works, provided that you comply with
169 | the terms of this License in conveying all material for which you do
170 | not control copyright. Those thus making or running the covered works
171 | for you must do so exclusively on your behalf, under your direction
172 | and control, on terms that prohibit them from making any copies of
173 | your copyrighted material outside their relationship with you.
174 |
175 | Conveying under any other circumstances is permitted solely under
176 | the conditions stated below. Sublicensing is not allowed; section 10
177 | makes it unnecessary.
178 |
179 | 3. Protecting Users' Legal Rights From Anti-Circumvention Law.
180 |
181 | No covered work shall be deemed part of an effective technological
182 | measure under any applicable law fulfilling obligations under article
183 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or
184 | similar laws prohibiting or restricting circumvention of such
185 | measures.
186 |
187 | When you convey a covered work, you waive any legal power to forbid
188 | circumvention of technological measures to the extent such circumvention
189 | is effected by exercising rights under this License with respect to
190 | the covered work, and you disclaim any intention to limit operation or
191 | modification of the work as a means of enforcing, against the work's
192 | users, your or third parties' legal rights to forbid circumvention of
193 | technological measures.
194 |
195 | 4. Conveying Verbatim Copies.
196 |
197 | You may convey verbatim copies of the Program's source code as you
198 | receive it, in any medium, provided that you conspicuously and
199 | appropriately publish on each copy an appropriate copyright notice;
200 | keep intact all notices stating that this License and any
201 | non-permissive terms added in accord with section 7 apply to the code;
202 | keep intact all notices of the absence of any warranty; and give all
203 | recipients a copy of this License along with the Program.
204 |
205 | You may charge any price or no price for each copy that you convey,
206 | and you may offer support or warranty protection for a fee.
207 |
208 | 5. Conveying Modified Source Versions.
209 |
210 | You may convey a work based on the Program, or the modifications to
211 | produce it from the Program, in the form of source code under the
212 | terms of section 4, provided that you also meet all of these conditions:
213 |
214 | a) The work must carry prominent notices stating that you modified
215 | it, and giving a relevant date.
216 |
217 | b) The work must carry prominent notices stating that it is
218 | released under this License and any conditions added under section
219 | 7. This requirement modifies the requirement in section 4 to
220 | "keep intact all notices".
221 |
222 | c) You must license the entire work, as a whole, under this
223 | License to anyone who comes into possession of a copy. This
224 | License will therefore apply, along with any applicable section 7
225 | additional terms, to the whole of the work, and all its parts,
226 | regardless of how they are packaged. This License gives no
227 | permission to license the work in any other way, but it does not
228 | invalidate such permission if you have separately received it.
229 |
230 | d) If the work has interactive user interfaces, each must display
231 | Appropriate Legal Notices; however, if the Program has interactive
232 | interfaces that do not display Appropriate Legal Notices, your
233 | work need not make them do so.
234 |
235 | A compilation of a covered work with other separate and independent
236 | works, which are not by their nature extensions of the covered work,
237 | and which are not combined with it such as to form a larger program,
238 | in or on a volume of a storage or distribution medium, is called an
239 | "aggregate" if the compilation and its resulting copyright are not
240 | used to limit the access or legal rights of the compilation's users
241 | beyond what the individual works permit. Inclusion of a covered work
242 | in an aggregate does not cause this License to apply to the other
243 | parts of the aggregate.
244 |
245 | 6. Conveying Non-Source Forms.
246 |
247 | You may convey a covered work in object code form under the terms
248 | of sections 4 and 5, provided that you also convey the
249 | machine-readable Corresponding Source under the terms of this License,
250 | in one of these ways:
251 |
252 | a) Convey the object code in, or embodied in, a physical product
253 | (including a physical distribution medium), accompanied by the
254 | Corresponding Source fixed on a durable physical medium
255 | customarily used for software interchange.
256 |
257 | b) Convey the object code in, or embodied in, a physical product
258 | (including a physical distribution medium), accompanied by a
259 | written offer, valid for at least three years and valid for as
260 | long as you offer spare parts or customer support for that product
261 | model, to give anyone who possesses the object code either (1) a
262 | copy of the Corresponding Source for all the software in the
263 | product that is covered by this License, on a durable physical
264 | medium customarily used for software interchange, for a price no
265 | more than your reasonable cost of physically performing this
266 | conveying of source, or (2) access to copy the
267 | Corresponding Source from a network server at no charge.
268 |
269 | c) Convey individual copies of the object code with a copy of the
270 | written offer to provide the Corresponding Source. This
271 | alternative is allowed only occasionally and noncommercially, and
272 | only if you received the object code with such an offer, in accord
273 | with subsection 6b.
274 |
275 | d) Convey the object code by offering access from a designated
276 | place (gratis or for a charge), and offer equivalent access to the
277 | Corresponding Source in the same way through the same place at no
278 | further charge. You need not require recipients to copy the
279 | Corresponding Source along with the object code. If the place to
280 | copy the object code is a network server, the Corresponding Source
281 | may be on a different server (operated by you or a third party)
282 | that supports equivalent copying facilities, provided you maintain
283 | clear directions next to the object code saying where to find the
284 | Corresponding Source. Regardless of what server hosts the
285 | Corresponding Source, you remain obligated to ensure that it is
286 | available for as long as needed to satisfy these requirements.
287 |
288 | e) Convey the object code using peer-to-peer transmission, provided
289 | you inform other peers where the object code and Corresponding
290 | Source of the work are being offered to the general public at no
291 | charge under subsection 6d.
292 |
293 | A separable portion of the object code, whose source code is excluded
294 | from the Corresponding Source as a System Library, need not be
295 | included in conveying the object code work.
296 |
297 | A "User Product" is either (1) a "consumer product", which means any
298 | tangible personal property which is normally used for personal, family,
299 | or household purposes, or (2) anything designed or sold for incorporation
300 | into a dwelling. In determining whether a product is a consumer product,
301 | doubtful cases shall be resolved in favor of coverage. For a particular
302 | product received by a particular user, "normally used" refers to a
303 | typical or common use of that class of product, regardless of the status
304 | of the particular user or of the way in which the particular user
305 | actually uses, or expects or is expected to use, the product. A product
306 | is a consumer product regardless of whether the product has substantial
307 | commercial, industrial or non-consumer uses, unless such uses represent
308 | the only significant mode of use of the product.
309 |
310 | "Installation Information" for a User Product means any methods,
311 | procedures, authorization keys, or other information required to install
312 | and execute modified versions of a covered work in that User Product from
313 | a modified version of its Corresponding Source. The information must
314 | suffice to ensure that the continued functioning of the modified object
315 | code is in no case prevented or interfered with solely because
316 | modification has been made.
317 |
318 | If you convey an object code work under this section in, or with, or
319 | specifically for use in, a User Product, and the conveying occurs as
320 | part of a transaction in which the right of possession and use of the
321 | User Product is transferred to the recipient in perpetuity or for a
322 | fixed term (regardless of how the transaction is characterized), the
323 | Corresponding Source conveyed under this section must be accompanied
324 | by the Installation Information. But this requirement does not apply
325 | if neither you nor any third party retains the ability to install
326 | modified object code on the User Product (for example, the work has
327 | been installed in ROM).
328 |
329 | The requirement to provide Installation Information does not include a
330 | requirement to continue to provide support service, warranty, or updates
331 | for a work that has been modified or installed by the recipient, or for
332 | the User Product in which it has been modified or installed. Access to a
333 | network may be denied when the modification itself materially and
334 | adversely affects the operation of the network or violates the rules and
335 | protocols for communication across the network.
336 |
337 | Corresponding Source conveyed, and Installation Information provided,
338 | in accord with this section must be in a format that is publicly
339 | documented (and with an implementation available to the public in
340 | source code form), and must require no special password or key for
341 | unpacking, reading or copying.
342 |
343 | 7. Additional Terms.
344 |
345 | "Additional permissions" are terms that supplement the terms of this
346 | License by making exceptions from one or more of its conditions.
347 | Additional permissions that are applicable to the entire Program shall
348 | be treated as though they were included in this License, to the extent
349 | that they are valid under applicable law. If additional permissions
350 | apply only to part of the Program, that part may be used separately
351 | under those permissions, but the entire Program remains governed by
352 | this License without regard to the additional permissions.
353 |
354 | When you convey a copy of a covered work, you may at your option
355 | remove any additional permissions from that copy, or from any part of
356 | it. (Additional permissions may be written to require their own
357 | removal in certain cases when you modify the work.) You may place
358 | additional permissions on material, added by you to a covered work,
359 | for which you have or can give appropriate copyright permission.
360 |
361 | Notwithstanding any other provision of this License, for material you
362 | add to a covered work, you may (if authorized by the copyright holders of
363 | that material) supplement the terms of this License with terms:
364 |
365 | a) Disclaiming warranty or limiting liability differently from the
366 | terms of sections 15 and 16 of this License; or
367 |
368 | b) Requiring preservation of specified reasonable legal notices or
369 | author attributions in that material or in the Appropriate Legal
370 | Notices displayed by works containing it; or
371 |
372 | c) Prohibiting misrepresentation of the origin of that material, or
373 | requiring that modified versions of such material be marked in
374 | reasonable ways as different from the original version; or
375 |
376 | d) Limiting the use for publicity purposes of names of licensors or
377 | authors of the material; or
378 |
379 | e) Declining to grant rights under trademark law for use of some
380 | trade names, trademarks, or service marks; or
381 |
382 | f) Requiring indemnification of licensors and authors of that
383 | material by anyone who conveys the material (or modified versions of
384 | it) with contractual assumptions of liability to the recipient, for
385 | any liability that these contractual assumptions directly impose on
386 | those licensors and authors.
387 |
388 | All other non-permissive additional terms are considered "further
389 | restrictions" within the meaning of section 10. If the Program as you
390 | received it, or any part of it, contains a notice stating that it is
391 | governed by this License along with a term that is a further
392 | restriction, you may remove that term. If a license document contains
393 | a further restriction but permits relicensing or conveying under this
394 | License, you may add to a covered work material governed by the terms
395 | of that license document, provided that the further restriction does
396 | not survive such relicensing or conveying.
397 |
398 | If you add terms to a covered work in accord with this section, you
399 | must place, in the relevant source files, a statement of the
400 | additional terms that apply to those files, or a notice indicating
401 | where to find the applicable terms.
402 |
403 | Additional terms, permissive or non-permissive, may be stated in the
404 | form of a separately written license, or stated as exceptions;
405 | the above requirements apply either way.
406 |
407 | 8. Termination.
408 |
409 | You may not propagate or modify a covered work except as expressly
410 | provided under this License. Any attempt otherwise to propagate or
411 | modify it is void, and will automatically terminate your rights under
412 | this License (including any patent licenses granted under the third
413 | paragraph of section 11).
414 |
415 | However, if you cease all violation of this License, then your
416 | license from a particular copyright holder is reinstated (a)
417 | provisionally, unless and until the copyright holder explicitly and
418 | finally terminates your license, and (b) permanently, if the copyright
419 | holder fails to notify you of the violation by some reasonable means
420 | prior to 60 days after the cessation.
421 |
422 | Moreover, your license from a particular copyright holder is
423 | reinstated permanently if the copyright holder notifies you of the
424 | violation by some reasonable means, this is the first time you have
425 | received notice of violation of this License (for any work) from that
426 | copyright holder, and you cure the violation prior to 30 days after
427 | your receipt of the notice.
428 |
429 | Termination of your rights under this section does not terminate the
430 | licenses of parties who have received copies or rights from you under
431 | this License. If your rights have been terminated and not permanently
432 | reinstated, you do not qualify to receive new licenses for the same
433 | material under section 10.
434 |
435 | 9. Acceptance Not Required for Having Copies.
436 |
437 | You are not required to accept this License in order to receive or
438 | run a copy of the Program. Ancillary propagation of a covered work
439 | occurring solely as a consequence of using peer-to-peer transmission
440 | to receive a copy likewise does not require acceptance. However,
441 | nothing other than this License grants you permission to propagate or
442 | modify any covered work. These actions infringe copyright if you do
443 | not accept this License. Therefore, by modifying or propagating a
444 | covered work, you indicate your acceptance of this License to do so.
445 |
446 | 10. Automatic Licensing of Downstream Recipients.
447 |
448 | Each time you convey a covered work, the recipient automatically
449 | receives a license from the original licensors, to run, modify and
450 | propagate that work, subject to this License. You are not responsible
451 | for enforcing compliance by third parties with this License.
452 |
453 | An "entity transaction" is a transaction transferring control of an
454 | organization, or substantially all assets of one, or subdividing an
455 | organization, or merging organizations. If propagation of a covered
456 | work results from an entity transaction, each party to that
457 | transaction who receives a copy of the work also receives whatever
458 | licenses to the work the party's predecessor in interest had or could
459 | give under the previous paragraph, plus a right to possession of the
460 | Corresponding Source of the work from the predecessor in interest, if
461 | the predecessor has it or can get it with reasonable efforts.
462 |
463 | You may not impose any further restrictions on the exercise of the
464 | rights granted or affirmed under this License. For example, you may
465 | not impose a license fee, royalty, or other charge for exercise of
466 | rights granted under this License, and you may not initiate litigation
467 | (including a cross-claim or counterclaim in a lawsuit) alleging that
468 | any patent claim is infringed by making, using, selling, offering for
469 | sale, or importing the Program or any portion of it.
470 |
471 | 11. Patents.
472 |
473 | A "contributor" is a copyright holder who authorizes use under this
474 | License of the Program or a work on which the Program is based. The
475 | work thus licensed is called the contributor's "contributor version".
476 |
477 | A contributor's "essential patent claims" are all patent claims
478 | owned or controlled by the contributor, whether already acquired or
479 | hereafter acquired, that would be infringed by some manner, permitted
480 | by this License, of making, using, or selling its contributor version,
481 | but do not include claims that would be infringed only as a
482 | consequence of further modification of the contributor version. For
483 | purposes of this definition, "control" includes the right to grant
484 | patent sublicenses in a manner consistent with the requirements of
485 | this License.
486 |
487 | Each contributor grants you a non-exclusive, worldwide, royalty-free
488 | patent license under the contributor's essential patent claims, to
489 | make, use, sell, offer for sale, import and otherwise run, modify and
490 | propagate the contents of its contributor version.
491 |
492 | In the following three paragraphs, a "patent license" is any express
493 | agreement or commitment, however denominated, not to enforce a patent
494 | (such as an express permission to practice a patent or covenant not to
495 | sue for patent infringement). To "grant" such a patent license to a
496 | party means to make such an agreement or commitment not to enforce a
497 | patent against the party.
498 |
499 | If you convey a covered work, knowingly relying on a patent license,
500 | and the Corresponding Source of the work is not available for anyone
501 | to copy, free of charge and under the terms of this License, through a
502 | publicly available network server or other readily accessible means,
503 | then you must either (1) cause the Corresponding Source to be so
504 | available, or (2) arrange to deprive yourself of the benefit of the
505 | patent license for this particular work, or (3) arrange, in a manner
506 | consistent with the requirements of this License, to extend the patent
507 | license to downstream recipients. "Knowingly relying" means you have
508 | actual knowledge that, but for the patent license, your conveying the
509 | covered work in a country, or your recipient's use of the covered work
510 | in a country, would infringe one or more identifiable patents in that
511 | country that you have reason to believe are valid.
512 |
513 | If, pursuant to or in connection with a single transaction or
514 | arrangement, you convey, or propagate by procuring conveyance of, a
515 | covered work, and grant a patent license to some of the parties
516 | receiving the covered work authorizing them to use, propagate, modify
517 | or convey a specific copy of the covered work, then the patent license
518 | you grant is automatically extended to all recipients of the covered
519 | work and works based on it.
520 |
521 | A patent license is "discriminatory" if it does not include within
522 | the scope of its coverage, prohibits the exercise of, or is
523 | conditioned on the non-exercise of one or more of the rights that are
524 | specifically granted under this License. You may not convey a covered
525 | work if you are a party to an arrangement with a third party that is
526 | in the business of distributing software, under which you make payment
527 | to the third party based on the extent of your activity of conveying
528 | the work, and under which the third party grants, to any of the
529 | parties who would receive the covered work from you, a discriminatory
530 | patent license (a) in connection with copies of the covered work
531 | conveyed by you (or copies made from those copies), or (b) primarily
532 | for and in connection with specific products or compilations that
533 | contain the covered work, unless you entered into that arrangement,
534 | or that patent license was granted, prior to 28 March 2007.
535 |
536 | Nothing in this License shall be construed as excluding or limiting
537 | any implied license or other defenses to infringement that may
538 | otherwise be available to you under applicable patent law.
539 |
540 | 12. No Surrender of Others' Freedom.
541 |
542 | If conditions are imposed on you (whether by court order, agreement or
543 | otherwise) that contradict the conditions of this License, they do not
544 | excuse you from the conditions of this License. If you cannot convey a
545 | covered work so as to satisfy simultaneously your obligations under this
546 | License and any other pertinent obligations, then as a consequence you may
547 | not convey it at all. For example, if you agree to terms that obligate you
548 | to collect a royalty for further conveying from those to whom you convey
549 | the Program, the only way you could satisfy both those terms and this
550 | License would be to refrain entirely from conveying the Program.
551 |
552 | 13. Use with the GNU Affero General Public License.
553 |
554 | Notwithstanding any other provision of this License, you have
555 | permission to link or combine any covered work with a work licensed
556 | under version 3 of the GNU Affero General Public License into a single
557 | combined work, and to convey the resulting work. The terms of this
558 | License will continue to apply to the part which is the covered work,
559 | but the special requirements of the GNU Affero General Public License,
560 | section 13, concerning interaction through a network will apply to the
561 | combination as such.
562 |
563 | 14. Revised Versions of this License.
564 |
565 | The Free Software Foundation may publish revised and/or new versions of
566 | the GNU General Public License from time to time. Such new versions will
567 | be similar in spirit to the present version, but may differ in detail to
568 | address new problems or concerns.
569 |
570 | Each version is given a distinguishing version number. If the
571 | Program specifies that a certain numbered version of the GNU General
572 | Public License "or any later version" applies to it, you have the
573 | option of following the terms and conditions either of that numbered
574 | version or of any later version published by the Free Software
575 | Foundation. If the Program does not specify a version number of the
576 | GNU General Public License, you may choose any version ever published
577 | by the Free Software Foundation.
578 |
579 | If the Program specifies that a proxy can decide which future
580 | versions of the GNU General Public License can be used, that proxy's
581 | public statement of acceptance of a version permanently authorizes you
582 | to choose that version for the Program.
583 |
584 | Later license versions may give you additional or different
585 | permissions. However, no additional obligations are imposed on any
586 | author or copyright holder as a result of your choosing to follow a
587 | later version.
588 |
589 | 15. Disclaimer of Warranty.
590 |
591 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
592 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
593 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
594 | OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
595 | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
596 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
597 | IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
598 | ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
599 |
600 | 16. Limitation of Liability.
601 |
602 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
603 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
604 | THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
605 | GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
606 | USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
607 | DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
608 | PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
609 | EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
610 | SUCH DAMAGES.
611 |
612 | 17. Interpretation of Sections 15 and 16.
613 |
614 | If the disclaimer of warranty and limitation of liability provided
615 | above cannot be given local legal effect according to their terms,
616 | reviewing courts shall apply local law that most closely approximates
617 | an absolute waiver of all civil liability in connection with the
618 | Program, unless a warranty or assumption of liability accompanies a
619 | copy of the Program in return for a fee.
620 |
621 | END OF TERMS AND CONDITIONS
622 |
623 | How to Apply These Terms to Your New Programs
624 |
625 | If you develop a new program, and you want it to be of the greatest
626 | possible use to the public, the best way to achieve this is to make it
627 | free software which everyone can redistribute and change under these terms.
628 |
629 | To do so, attach the following notices to the program. It is safest
630 | to attach them to the start of each source file to most effectively
631 | state the exclusion of warranty; and each file should have at least
632 | the "copyright" line and a pointer to where the full notice is found.
633 |
634 |
635 | Copyright (C)
636 |
637 | This program is free software: you can redistribute it and/or modify
638 | it under the terms of the GNU General Public License as published by
639 | the Free Software Foundation, either version 3 of the License, or
640 | (at your option) any later version.
641 |
642 | This program is distributed in the hope that it will be useful,
643 | but WITHOUT ANY WARRANTY; without even the implied warranty of
644 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
645 | GNU General Public License for more details.
646 |
647 | You should have received a copy of the GNU General Public License
648 | along with this program. If not, see .
649 |
650 | Also add information on how to contact you by electronic and paper mail.
651 |
652 | If the program does terminal interaction, make it output a short
653 | notice like this when it starts in an interactive mode:
654 |
655 | Copyright (C)
656 | This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
657 | This is free software, and you are welcome to redistribute it
658 | under certain conditions; type `show c' for details.
659 |
660 | The hypothetical commands `show w' and `show c' should show the appropriate
661 | parts of the General Public License. Of course, your program's commands
662 | might be different; for a GUI interface, you would use an "about box".
663 |
664 | You should also get your employer (if you work as a programmer) or school,
665 | if any, to sign a "copyright disclaimer" for the program, if necessary.
666 | For more information on this, and how to apply and follow the GNU GPL, see
667 | .
668 |
669 | The GNU General Public License does not permit incorporating your program
670 | into proprietary programs. If your program is a subroutine library, you
671 | may consider it more useful to permit linking proprietary applications with
672 | the library. If this is what you want to do, use the GNU Lesser General
673 | Public License instead of this License. But first, please read
674 | .
675 |
--------------------------------------------------------------------------------