440 likes | 1.04k Views
Introduction to Design patterns Singleton pattern. Object Orientation Basics. Abstraction Concentrates only the outside view - the interface Encapsulation
E N D
Introduction to Design patterns Singleton pattern Introduction to Design Patterns
Object Orientation Basics • Abstraction • Concentrates only the outside view - the interface • Encapsulation • Combining the data and actions of objects into a single item (a class) and hiding the implementation details from the client program • Inheritance • Common features in superclass, subclasses inherit these features and add their own • Polymorphism • the ability of different objects to respond, each in its own way, to the same message. Introduction to Design Patterns
Object Orientation Metrics • Cohesion • Objects should have responsibility for set of closely related tasks • Coupling • How interconnected different classes are • Loose coupling means that changes in one class should not require changes in other classes Introduction to Design Patterns
Where do patterns come from? • Designing good reusable Object-Oriented Software is hard. The solution should solve your problem, but should be general enough to be reused for the same kind of problem. • Expert software designers tend to reuse the good designs they’ve created again and again. They don’t want to reinvent a solution to a problem they’ve already solved • In the course of time, good and successful designs end up becoming generalised as patterns Introduction to Design Patterns
What is a pattern? • Here are several definitions of a design pattern: • A general solution to a common problem in software design (not implementation) • Best practices of experienced object-oriented software developers • Descriptions of communicating objects and classes that are customised to solve a general design problem in a particular context • This means a pattern can never be transformed directly into code. It needs to be tailored to a specific problem Introduction to Design Patterns
More pattern definitions “Patterns identify and specify abstractions that are above the level of single classes and instances, or of components” GoF, 93 “Design patterns are recurring solutions to design problems you see over and over” Alpert et al., 98 Introduction to Design Patterns
Patterns • Maximise code reuse • Minimise re-implementation • Increase cohesion • Reduce coupling • Patterns are not a panacea • There are drawbacks as well as benefits • Often increased complexity Introduction to Design Patterns
What’s their history? • Late 1970s, Christopher Alexander developed a pattern language for the built environment. • http://downlode.org/Etext/Patterns/ • He was an architect himself (among other things) and seems to have been reacting to the arrogance and grossness of so much modern architecture (especially in the 60s and 70s). • Mediaeval cities, for example, are attractive and harmonious. • He tried to discern patterns in architecture that worked, rather than lay down the law according to some architect-centred aesthetic Introduction to Design Patterns
An example: 67 Common Land • May be part of Accessible Green (60), House Cluster (37), Row Houses (38), Housing Hill (39), Work Community (41). • Conflict Without common land no social system can survive. • Resolution Give over 25 per cent of the land in house clusters to common land which touches, or is very very near, the homes which share it. Basic: be wary of the automobile; on no account let it dominate this land. • May contain South Facing Outdoors (105), Positive Outdoor Space (106), Hierarchy of Open Space (114), Outdoor Room (163), Local Sports (72). Introduction to Design Patterns
And so on to software engineering • In the late 1980s, the idea of patterns started to be adopted by programmers. • Original catalogue “Design Patterns” by Gamma, Helm, Johnson and Vlissides, Addison -Wesley, 1995 • lists 23 standard patterns, their uses, advantages and drawbacks • all patterns described in C++ terms • Since then, lots of different books have been published, among them • Java Design Patterns by James Cooper (2000) • Head First Design Patterns by Eric and Elisabeth Freeman (2004) Introduction to Design Patterns
Patterns speed up software development • They have been proven • Patterns reflect the experience, knowledge and insights of developers who have successfully used these patterns in their own work. • They are reusable • Patterns provide a ready-made solution that can be adapted to different problems as necessary • They create a shift of focus to a higher level of abstraction: pattern level instead of class level • We’ve got design building bricks that we know works well. We can therefore work on trying to combine them together instead of focusing on details like “what should be the relation between those 2 classes?” Introduction to Design Patterns
Patterns make maintenance easier • They are expressive • Patterns provide a common vocabulary of solutions that can express large solutions succinctly for coders and architects familiar with them • They improve code readability • Classes are clearly defined and the link between them is clear Introduction to Design Patterns
Three categories of pattern • Creational Patterns • deal with ways to create instances of objects • Structural Patterns • describe how classes and objects can be combined to form larger structures • Behavioural Patterns • are concerned with communications between objects • Other patterns exist in specific areas such as Concurrency programming • Covered later for the Threads stage Introduction to Design Patterns
Classification of Patterns CREATIONAL PATTERNS Abstract factory Builder Factory method Prototype Singleton STRUCTURAL PATTERNS Adapter Bridge Composite Decorator Facade Flyweight Proxy BEHAVIORAL PATTERNS Chain of responsibility Command Interpreter Iterator Mediator Memento Observer State Strategy Template method Visitor Introduction to Design Patterns
Pattern structure • A name, so that it’s easy to talk about the pattern • The problem that the pattern addresses • The solution • The consequences of using the pattern Introduction to Design Patterns
Diverse approaches to re-use • Patterns • Abstract designs • Frameworks • concrete, implemented, rather than abstract • Components • Somewhere between a framework and an object. • Class libraries • Smaller scope and not domain specific • Objects • Inheritance Introduction to Design Patterns
A Conceptual View Abstraction = 1/Specificity Patterns Frameworks Components Libraries/APIs Objects Introduction to Design Patterns
Patterns in ASE • We’ll only cover a few, to give you a flavour for them • Add them to your coursework • If you feel they are appropriate • If you have time • You’ll probably need to refactor your code Introduction to Design Patterns
SINGLETON PATTERN Introduction to Design Patterns
Singleton Pattern • Use to ensure only one instance of this class in the system, while allowing other classes to get access to this instance. • Useful for objects such as printSpoolers and filesystems, which are accessed by various objects in a system • For writing to a log file • A Window manager • An NextNumber manager, providing the next number in a sequence • Provides • a single point to access it • controls access to instance • avoids the use of a global variable Introduction to Design Patterns
Singleton • singleton : Singleton • Singleton() + getInstance() : Singleton Singleton class diagram Introduction to Design Patterns
Singleton – eager instantiation • Eager instantiation performed at time class is loaded public class Singleton { private static Singleton instance = new Singleton (); //private constructor, access only within class private Singleton () { ... } //public getInstance(), accessible everywhere public static Singleton getInstance() { return instance; } } Introduction to Design Patterns
Singleton – lazy instantiation • Lazy instantiation performed when/if get method is called – useful if object resource-expensive public class Singleton { private static Singleton instance; //private constructor, access only within class private Singleton () { ... } //public getInstance(), accessible everywhere public static Singleton getInstance() { if (instance == null) instance = new Singleton(); return instance; } } Introduction to Design Patterns
NextNumber Example • The single object provides the next number in a sequence • Keeps the last number as an instance variable public class NextNumber { private int number; public NextNumber() { this.number = 0; } public int getNext() { number++; return number; } } Introduction to Design Patterns
Convert NextNumber to Singleton (1) • Merge Singleton class with NextNumber class • See this and next slide public class NextNumber { private static NextNumber instance; private int number; //private constructor, access only within class private NextNumber () { number = 0; } Introduction to Design Patterns
Convert NextNumber to Singleton (2) //public getInstance(), accessible everywhere public static NextNumber getInstance() { if (instance == null) instance = new NextNumber(); return instance; } //NextNumber get method public int getNext() { number++; return number; } } Introduction to Design Patterns
Use NextNumber class public class UseNextNumber { public static void main(String arg[]) { NextNumber next = NextNumber.getInstance(); for (int i = 0; i < 5; i++) { System.out.println(next.getNext()); } next = NextNumber.getInstance(); for (int i = 0; i < 5; i++) { System.out.println(next.getNext()); } } } Introduction to Design Patterns
Singleton in Multithreaded Environment • Does this work in a multithreaded environment? • Eager instantiation is OK • Lazy instantiation is susceptible to race condition Thread 1 Thread 2 if ( instance == null ) if ( instance == null ) instance = new Singleton(); return instance; instance = new Singleton(); return instance; Introduction to Design Patterns
Synchronised methods • Lazy instantiation — if building object not certain, but expensive • Multithreaded environment would allow two (or more) objects to be created • synchronized forces only one thread to access the method at a time public static synchronized Singleton getInstance() { if ( instance == null ) instance = new Singleton(); return instance; } • Expensive if getInstance is used extensively Introduction to Design Patterns
2-phase test • 2-phase test delays the synchronisation until the new instance actually needs to be created public volatile static Singleton getInstance () { if ( instance == null ) { synchronized (Singleton.class) { if ( instance == null ) instance = new Singleton(); } } return instance; } Introduction to Design Patterns
Singleton summary • Provides access to only one object, through get method rather than constructor • Lazy instantiation good if building the object is expensive • Lazy instantiation is not safe in multithreaded environment • Solve by using synchronized in method header • 2-phase test if getSingleton is used extensively Introduction to Design Patterns
Singleton v static class • ? Why not use public class StaticSingleton { private static Next d = new Next(); public static Next getNext() { return d; } } • Singleton pattern is more flexible • Using objects rather than classes • Can implement interfaces • Can extend to 1 .. N instead of just 1 Introduction to Design Patterns