22.03.31 - Design Patterns
Patterns
Patterns help us to identify ways which a problem can be solved. Identify the pattern for the problem, then look at how people have solved this in the past
Responsibilities and good design
If a class has multiple types of responsibilities, usually better to split it into multiple classes. Can 'switch out' combinations of implementations of these responsibilities Have strategy pattern, observer pattern, iterator pattern
Some final patterns
Creational
Creational patterns are patterns related to creation of objects
- Singleton: only one instance of this class
- Factory - wrap up the creation of another object(s), particularly when you don't know what to create
- Both use a method to create the object, not new directly
Singleton
You create one instance when needed. Basic singleton in java uses a static method.
- A static member is in the class not each instance, shared between all instances. One copy only per class.
- Static members are associated with the class rather tan the object. Can share it across other objects.
- Keep track of the one object created in a static member variable, never create an object of the class manually
Factory Pattern
- Factory is an object which manufactures other objects
- We will concentrate on simple examples, although there are more complex powerful examples of this
- Dont need to know which precise sub-class it will create - can let the factory decided
- Controlling the creation of different objects can have a number of uses
Singleton vs Factory
Both have a method for creating objects for you. Shared objects for singleton, multiple objects for the factory. Simple factory has a 'factory' object which is responsible for creating the objects. Singleton has a static member function/method
Design Patterns Summary
- Observer: Tell me when something happens
- Strategy: Lets another object modify the behaviour of an object
- Iterator: Lets you iterate through the contents
- Singleton: Create just one instance and use it anywhere
- Simple Factory: Delegate the job of choosing which lass to actually create to another object
Final Summary
- Objects: Collection of data, set of methods which act up on the data
- Access Permissions: Packages are very important because of access privileges in Java
- Public - Anything can access this
- Protected - This class + this package + subclasses can access this
- nothing(package) - This class + this package can access it
- Private - Only this class can access this