CSC/ECE 517 Fall 2011/ch4 4h as

From Expertiza_Wiki
Jump to navigation Jump to search

Introduction

Software Design Patterns

Singleton Pattern

In software engineering the singleton pattern is a creational pattern which is used to ensure that not more than one object is ever created for a class. The singleton also provides a point of global access. There may be various reasons that necessitate such a requirement for a class.

Common Applications

The class may represent the global state of the system or the class may correspond to a master logger which writes into the log file. Some other places where the singleton pattern is applicable are device drivers, registry settings, etc.

Implementation

There are many ways of implementing the singleton pattern. The most common way is to have a method which creates an instance of the object if it does not already exist. Otherwise the existing reference is returned. To make sure that multiple instances are not created the constructor is made private. Also the object which stores the single instance is made a class variable and is thus not tied to any particular instance of the class.

public class Singleton {
    private static Singleton singletonInstance;
    private Singleton() {  }
    public static Singleton getInstance() {
            if (singletonInstance == null) {
                   singletonInstance = new Singleton();
            }
            return singletonInstance;
    }
}

Adapter Pattern

Command Pattern

Strategy Pattern

Conclusion

References