Skip to main content

Posts

Showing posts with the label Design Patterns

What is Singleton Pattern?

The singleton pattern is a design pattern that is used to restrict instantiation of a class to one object Singletons (being often a bad choice) are classes that can have only one instance throughout the whole program. For example a SingletonConfigFile might look like this. It is for reading one file only. It would make sense for this to be a config file. If your class can be instantiated more than once, for different files, it is not singleton. Don't use this code - it doesn't take into account concurrency problems which are a whole different area of discussion.    public SingletonConfigFile {    private static String filename = "config.xml";    private File file;    private static SingletonConfigFile instance;

Behavioral Patterns - Interpreter Pattern

The Interpreter Pattern defines a grammatical representation for a language and an interpreter to interpret the grammar. The best example you can get for this is Java itself which is an interpreted language. It converts the code written in English to a byte code format so as to make possible for all the operating systems to understand it. This quality of it makes it platform independent. The development of languages can be done when you find different cases but, somewhat similar, it is advantageous to use a simple language which can be interpreted by the system and can deal with all these cases at the same time. To make this interpreter clearer, let’s take an example. The “musical notes” is an “Interpreted Language”. The musicians read the notes, interpret them according to “Sa, Re, Ga, Ma…” or “Do, Re, Me… ” etc and play the instruments, what we get in output is musical sound waves. Think of a program which can take the Sa, Re, Ga, Ma etc and produce the sounds for the frequenc...

What is Bridge Pattern and Marker Interface

Bridge Pattern as the name suggests is used maily to decouple the interface and the class implementing the interface. Another obvious advantage is the extensibility provided in terms of Future enhancements. Also, hiding the actual implementation from the Client. Marker Interfaces are interfaces in Java that have no behavior. In other words, they are just empty interface definitions. For example in the Java API java.io.Serializable, Cloneable etc. All interfaces can act as marker interface but null interfaces are the most suited for it. also every interface has a boolean flag and that boolean flag goes for the entire generation of classes implenting that interface. I understand this boolean flag is the marker. What I want to know how this stuff is working in detail? Marker Interface: One of the "clean" features of the Java programming language is that it mandates a separation between interfaces (pure behavior) and classes (state and behavior). Interfaces are used in Ja...

When to use "private" constructor?

-- The private constructors are used in the following situation: When you implement singletons or factory design pattern. Do not want people to instantiate your class directly. e.g., new MyObject();. For example, all of your method and fields are static, you may need to add a private default constructor (if you do not have it, compiler will add one for you that is not what you want). Such way can enforce that people can not accidently use "new".

Creational Patterns - Abstract Factory Pattern

This pattern is one level of abstraction higher than factory pattern. This means that the abstract factory returns the factory of classes. Like Factory pattern returned one of the several sub-classes, this returns such factory which later will return one of the sub-classes. Let’s understand this pattern with the help of an example. Suppose we need to get the specification of various parts of a computer based on which work the computer will be used for. The different parts of computer are, say Monitor, RAM and Processor. The different types of computers are PC, Workstation and Server. So, here we have an abstract base class Computer. package creational.abstractfactory; public abstract class Computer { /** * Abstract method, returns the Parts ideal for * Server * @return Parts */ public abstract Parts getRAM(); /** * Abstract method, returns the Parts ideal for * Workstation * @return Parts */ public abstract Parts getProcessor(); /** * Abstract method...

Structural Patterns - Composite Pattern

In developing applications, we come across components which are individual objects and also can be collection of objects. Composite pattern can represent both the conditions. In this pattern, you can develop tree structures for representing part-whole hierarchies. TThe most common example in this pattern is of a company’s employee hierarchy. We here will also take the same example. The employees of a company are at various positions. Now, say in a hierarchy, the manager has subordinates; also the Project Leader has subordinates, i.e. employees reporting to him/her. The developer has no subordinates. So, let’s have a look at the class Employee: This is a simple class with getters and setters for attributes as name, salary and subordinates. Employee.java package structural.composite; import java.util.Vector; public class Employee { private String name; private double salary; private Vector subordinates; public Vector getSubordinates() { return subordinates...

Creational Patterns - Prototype Pattern

The prototype means making a clone. This implies cloning of an object to avoid creation. If the cost of creating a new object is large and creation is resource intensive, we clone the object. We use the interface Cloneable and call its method clone() to clone the object. Again let’s try and understand this with the help of a non-software example. I am stressing on general examples throughout this write-up because I find them easy to understand and easy to accept as we all read and see them in day-to-day activity. The example here we will take will be of a plant cell. This example is a bit different from the actual cloning in a way that cloning involves making a copy of the original one. Here, we break the cell in two and make two copies and the original one does not exist. But, this example will serve the purpose. Let’s say the Mitotic Cell Division in plant cells.   Let’s take a class PlantCell having a method split(). The plant cell will implement the interface Cloneable. Foll...

Structural Patterns - Facade Pattern

Facade as the name suggests means the face of the building. The people walking past the road can only see this glass face of the building. They do not know anything about it, the wiring, the pipes and other complexities. The face hides all the complexities of the building and displays a friendly face. This is how facade pattern is used. It hides the complexities of the system and provides an interface to the client from where the client can access the system. In Java, the interface JDBC can be called a facade. We as users or clients create connection using the "java.sql.Connection" interface, the implementation of which we are not concerned about. The implementation is left to the vendor of driver. Let's try and understand the facade pattern better using a simple example. Let's consider a store. This store has a store keeper. In the storage, there are a lot of things stored e.g. packing material, raw material and finished goods. You, as client want access to ...

Behavioral Patterns - Mediator Pattern

The mediator pattern deals with the complexity which comes in the coding when number of classes increase. I will explain this. When we begin with development, we have a few classes and these classes interact with each other producing results. Now, consider slowly, the logic becomes more complex and functionality increases. Then what happens? We add more classes and they still interact with each other but it gets really difficult to maintain this code now. Mediator pattern takes care of this problem. It makes the code more maintainable. It promotes loose-coupling of classes such that only one class (Mediator) has the knowledge of all the classes, rest of the classes have their responsibilities and they only interact with the Mediator. A very common example can be airplanes interacting with the control tower and not among themselves. The control tower knows exactly, where each of the airplanes is, and guides them whereas the airplanes have their own responsibilities of landing and take...

Behavioral Patterns - Command Pattern

This is another of the data-driven pattern. The client invokes a particular module using a command. The client passes a request, this request gets propagated as a command. The command request maps to particular modules. According to the command, a module is invoked. This pattern is different from the Chain of Responsibility in a way that, in the earlier one, the request passes through each of the classes before finding an object that can take the responsibility. The command pattern however finds the particular object according to the command and invokes only that one. It’s like there is a server having a lot of services to be given, and on Demand (or on command), it caters to that service for that particular client. A classic example of this is a restaurant. A customer goes to restaurant and orders the food according to his/her choice. The waiter/ waitress takes the order (command, in this case) and hands it to the cook in the kitchen. The cook can make several types of food...

Behavioral Patterns - Iterator Pattern

  The Iterator pattern is one, which allows you to navigate through a collection of data using a common interface without knowing about the underlying implementation. Iterator should be implemented as an interface. This allows the user to implement it anyway its easier for him/her to return data. We use iterators quite frequently in everyday life. For example, remote control of TV. Any remote control we use, either at home/hotel or at a friend's place, we just pick up the TV remote control and start pressing Up and Down or Forward and Back keys to iterate through the channels. What sort of interface can Iterator be in case of Remote Controls? /** * Iterator interface has method declarations for iterating through * TV channels. All remote controls implement Iterator. */ public interface Iterator {   public Channel nextChannel(int currentChannel); public Channel prevChannel(int currentChannel); }// End of interface The channel iterator is common for all t...

Structural Patterns - Proxy Pattern

The proxy pattern is used when you need to represent a complex with a simpler one. If creation of object is expensive, its creation can be postponed till the very need arises and till then, a simple object can represent it. This simple object is called the "Proxy" for the complex object The cases can be innumerable why we can use the proxy. Let's take a scenario. Say, we want to attach an image with the email. Now, suppose this email has to be sent to 1 lakh consumers in a campaign. Attaching the image and sending along with the email will be a very heavy operation. What we can do instead is, send the image as a link to one of the sevlet. The place holder of the image will be sent. Once the email reaches the consumer, the image place holder will call the servlet and load the image at run time straight from the server. Let's try and understand this pattern with the help of a non-software example as we have tried to do throughout this article. Bank.java

Structural Patterns - Bridge Pattern

The Bridge Pattern is used to separate out the interface from its implementation. Doing this gives the flexibility so that both can vary independently. The best example for this is like the electric equipments you have at home and their switches. For e.g., the switch of the fan. The switch is the interface and the actual implementation is the Running of the fan once its switched-on. Still, both the switch and the fan are independent of each other. Another switch can be plugged in for the fan and this switch can be connected to light bulb. Let’s see how we can convert this into a software program. Switch is the interface having two functions, switchOn() and switchOff(). Here is the sample code for Switch.

J2EE Design Patterns

Structural Patterns - Flyweight Pattern

  The pattern here states about a mechanism by which you can avoid creating a large number of object instances to represent the entire system. To decide if some part of your program is a candidate for using Flyweights, consider whether it is possible to remove some data from the class and make it extrinsic. If this makes it possible to reduce greatly the number of different class instances your program needs to maintain, this might be a case where Flyweights will help. The typical example you can see on this in every book will be of folders. The folder with name of each of the company employee on it, so, the attributes of class Folder are: 'Selected' , 'Not Selected' and the third one is 'employeeName'. With this methodology, we will have to create 2000 folder class instances for each of the employees. This can be costly, so we can create just two class instances with attributes 'selected' and 'not selected' and set the employee's name...

Structural Patterns - Adapter Pattern

The Adapter pattern is used so that two unrelated interfaces can work together. The joining between them is called an Adapter. This is something like we convert interface of one class into interface expected by the client. We do that using an Adapter. Let’s try and understand this with the help of an example. Again, I will like to take a general example. We all have electric sockets in our houses of different sizes and shapes. I will take an example of a socket of 15 Ampere. This is a bigger socket and the other one which is smaller is of 5 Ampere. A 15 Amp plug cannot fit into a 5 Amp socket. Here, we will use an Adapter. The adapter can be called a connector here. The connector connects both of these and gives output to the client plug which is of 5 Amp. The Adapter is something like this. It will be having the plug of suitable for 15 Amp and a socket suitable for a 5 Amp plug. So, that the 5 Amp plug which here is the client can fit in and also the server which here is th...