RSS

What is Façade design pattern?


Well, Façade is a design pattern that is being used by most of the programmers out there even without knowing.

Façade design pattern is similar to Adapter design pattern in a way, both acts as interfaces (middle layer). As we discussed earlier, Adaptor design pattern is a wrapper to avoid incompatibilities or to reduce complexities. E.g.: Java, c# Wrapper libraries for 3D programming or Image processing allows users to use defined functions than working with complex mathematics in these research areas.

Now let’s see how Façade hides some complexities (or just hiding large body of code) by introducing a middle layer.

Let’s take the scenario where you were assigned to create a Computer object.

After the completion you can ask the user to use the Computer. And he will first need to run powerUp() method to power up the system. Then, postMethod() which will run POST. Later he’ll need to run loadOS() method load the OS. Finally he will be able to start working.


class Computer {

public Computer() {
}

public void powerUP() { // ...
}

public void postMethod() { // ...
}

public void loadOS() { // ...
}

// ...
}

public class ExecComputer {
// User executes following ...

public static void main(String[] args) {

Computer computer = new Computer();
computer.powerUP();
computer.postMethod();
computer.loadOS();
// ...
}
}

I’m sure you notice the problem here. It’s not required for the user to run all these methods and it’s really a headache for users. (You can understand there are more methods to come like this)

So what’s the fix here? Yes you probably guessed correctly. We need to introduce a simple run() method which executes all these methods from the back in proper sequence. So user just have to remember the run() method.

Following code presents the fix;


class Computer {

private Computer computer;

public Computer() {
computer = new Computer();
}

private void powerUP() { // ...
}

private void postMethod() { // ...
}

private void loadOS() { // ...
}

public void run() {
computer.powerUP();
computer.postMethod();
computer.loadOS();
// ...
}

// ...

}

public class ExecComputer {
/**
* User executes following ...
*/
public static void main(String[] args) {

Computer computer = new Computer();
computer.run();
// ...
}
}

Well there you go. Simple as that.

I know what you think right now. Is there a design pattern for this? 🙂 Yes mate felt the same way when I first knew this. But don’t think Facade is all about this code, think about this concept and keep it in mind. You may miss this trick when you got your brain inside a massive code base. See you soon 🙂

 
 

Tags: , ,

Chain of responsibility / Chain of command Design pattern


Following is a comprehensive discussion about chain of responsibility (command) design pattern. For convenience I’ll be using the word “responsibility” over “command”.

Hi guys, this is another widely used design pattern which is serving a similar purpose as of observer design pattern by notifying objects when something happens. [If you are interested about learning observer design pattern you can refer to this article].

As you know, Observer design pattern handles notifications parallel as follows.

Observer Design Pattern

However, chain of responsibility works in a serial manner as opposite to above method.

Chain of responsibiltity design pattern

Think we are passing on objects of different shapes along the line and there are holes with different shapes corresponding to the sizes and shapes of possible shapes coming down the line. And a particular hole will only catch the objects of similar shapes coming and others are continued down the line and if no hole catches it, it will be exited. If a particular shape is being caught, further travelling of that particular object is not needed.

This is the methodology we use in chain of responsibility design pattern and think of those shaped objects as notifications and holes as objects that are willing to accept intended notifications.

This design pattern can be used when your observers are not logically equal as such and the main idea is to avoid coupling of sender to its observers. This pattern provide the capability for any observer to handle a particular notification unlike in observer, observers have decidability power.

Consider an organization consists of lower, middle and higher level management with different levels of responsibilities. Assume that a problem related to employees are to be handled by lower level management and lower level management problems are to be addressed by middle levels and their problems will be addressed by higher levels. Let’s build our code based on this scenario.

In order to take control of all observing objects, let’s first create an interface called “ResolveInterface”.


public interface ResolveInterface {

public void resolve(int problemID);
}

Then we’ll construct 3 observers as follows by implementing the above interface. In order to chain each other we’ll provide a reference to the object next to each object. This can be set when each object is being created therefore object constructor can be used for this (See code below).

LowLevelManagement Class;

public class LowLevelManagement implements ResolveInterface {

final int EMPLOYEE_RELATED_PROB = 1;
ResolveInterface successor;

public LowLevelManagement(MiddleLevelManagement s) {
successor = s;
}

@Override
public void resolve(int problemID) {
if (EMPLOYEE_RELATED_PROB == problemID) {
System.out.println("resolving Problem type " + problemID + " by "
+ this.getClass().getSimpleName());
} else {
successor.resolve(problemID);
}
}
}

MiddleLevelManagement Class;

public class MiddleLevelManagement implements ResolveInterface {

final int LOW_MNG_RELATED_PROB = 2;
ResolveInterface successor;

public MiddleLevelManagement(HighLevelManagement s) {
successor = s;
}

@Override
public void resolve(int problemID) {
if (LOW_MNG_RELATED_PROB == problemID) {
System.out.println("resolving Problem type " + problemID + " by "
+ this.getClass().getSimpleName());
} else {
successor.resolve(problemID);
}

}

}

HighLevelManagement Class;

public class HighLevelManagement implements ResolveInterface {

final int MIDDLE_MNGR_RELATED_PROB = 3;
ResolveInterface successor;

public HighLevelManagement() {

}

@Override
public void resolve(int problemID) {
System.out.println("resolving Problem type " + problemID + " by "
+ this.getClass().getSimpleName());
}
}

So it’s as simple as that. Now it’s time for us to test the code and following class will test it.

public class TestChainOfCommand {

final int EMPLOYEE_RELATED_PROB = 1;
final int LOW_MNG_RELATED_PROB = 2;
final int MIDDLE_MNGR_RELATED_PROB = 3;

public static void main(String[] args) {
HighLevelManagement highLevlMngr = new HighLevelManagement();
MiddleLevelManagement middlevlMngr = new MiddleLevelManagement(
highLevlMngr);
LowLevelManagement lowLevlMngr = new LowLevelManagement(middlevlMngr);

lowLevlMngr.resolve(3);
lowLevlMngr.resolve(2);
lowLevlMngr.resolve(1);
}
}

Following are the outputs;Chain of commandresult

So that’s it. You just learnt another widely used design pattern. So next time you want to handle notifications in an loosely coupled manner this pattern should create a neuron pattern in your brain :D.

I’ll be back soon with another useful post. C ya!

 
Leave a comment

Posted by on December 25, 2012 in Design patterns, Java

 

Tags: , ,

Alterations for Singleton pattern?


Following section describes about alterations to singleton design pattern among many programmers.

Since this is an innovative world many programmers are coming up with alterations to design patterns. I really encourage all of you guys to do the same but by knowing the depth and breadth of the design pattern you working with and understanding why and how it does things. Today I’m going to discuss about some alteration they suggest for singleton pattern which I have here and let’s discuss what are the problems attached with those methods.

1)      Having a global object instead of a singleton.

Yep, many might think why not because it should work just fine.

But wait a minute don’t lose OOP. As I have discussed earlier design patterns are an extension for OOP and it is trying to take it to a higher level. By introducing global object concept you are probably ruining one golden principle in OOP called “ENCAPSULATION”. You are binding your package with global objects. Also with this approach it is possible to have many objects in other packages too which will lead to issues that will hit you back hard and will kill your time, etc.

2)      Another suggestion is to use static variables. But here also you might be possibly ruining the “ENCAPSULATION” and “ABSTRACTION” principles. It doesn’t allow the singleton class to have control over object creation it’s just keeping the single value which can be copied over many objects yet the value remains same. As you can understand this might lead to many unnecessary objects even and probably at the long run many will have difficult time debugging codes. So it ruins one major concern of design patterns.

3)      Some developers would like to sub class the singleton class, this is OK as long as you keep your codes under your control but this might lead to some problems when somebody uses these sub classes to create a normal class. Therefore best way is to avoid these possible anomalies.

Possible Issues;

It is possible to use multiple class loaders within your application, where each class loader uses its own namespace. So it’s possible to have multiple singleton objects as one per each. Therefore you have to ensure all class loaders coordinates and keeps only one singleton object for entire application.

Prior to Java 1.2(long time back 🙂 ), garbage collector had a bug where it swallows the singleton object if there aren’t any references to the Singleton object outside of its class. Later it was solved.

Think about the possibility of cloning via clone() method.

There are quite a few debates regarding creating Singleton via ENUMs rather than using Classes. I’ll get back to you on that.

As I said it’s an innovative world 🙂

 
1 Comment

Posted by on December 24, 2012 in Design patterns, Java

 

Tags: , ,

Observer Design Pattern


Observer Design Pattern tutorial with design diagrams and code examples.

Overview

o   Background

o   Scenario

o   Implementation

o   Does java ship with Observer implementations?

Background

Well it’s time for another design pattern, and this time we’ll look in to the observer design pattern. Observer design pattern acts according to the meaning of its name and you’ll understand it fully after covering this tutorial. So let’s dive in to the scenario.

Scenario

Think of a situation where you have to maintain a colony where new members can join in. The colony is having different requirements at times and this message should be transferred to its members in order to get supplies from them. As a result the colony will grow gradually.

Basically programmers should allow following functions.

  • New members should be able to register in.
  • Members should be able to unregister at their will.
  • Colony should have a way of communicating its requirements to the current members.

The observer design pattern will consist of two different kinds of objects named as the Subject and Observers. In this case the subject will be the colony and members will act as observers who are observing the Subject. Furthermore, as soon as a requirement arises at the subject (Colony), all the observers will be notifyied. Following figure shows the performed functionalities in observer pattern.

So keeping this simple idea in our minds let’s start coding.

Implementation

According to the above diagram, Subject should include three major functions for registering, notifying and unregistering observers.

As designers it’s often a good practice to impose a structure for programmers to work on. In this case we should create interfaces for both Subject and Observer which will be implemented by programmers to create actual objects. Therefore the intended architecture won’t be changed.

Subject interface will consist of those three methods discussed earlier while Observer interface would include an update method which will be executed when a particular notification reaches the observer.

Following are the two interfaces.

Figure 4 – Subject Interface

Figure 5 – Observer Interface

So the designers’ job is mostly done and it’s up to the programmers to understand the design architecture and use these interfaces to implement the scenario. Programmers will create the actual Subject and Observers as follows.

Note that there can be different kinds of members in the colony (E.g. – member, team leader, manager), and we can implement them in the same manner as follows.

Figure 7 – Concrete Observer

Since everything is set up, we will test this out to see how it works! 🙂

And this will provide the expected output as;

That means that these different kinds of members have received the message from colony and so they can proceed accordingly.

So what are the benefits that you can identify in this pattern?

It’s closed for modifications while opened for extension. If we are to notify many new members or to remove notifying earlier members we can just do it without affecting the program compile time. Registering and unregistering is handled at run time so it’s easier to manage observers as per the requirement at run time.

We do not need to change the core codes and compile them again, which might even introduce bugs to the core code and will have to go through tedious testing including old and newly integrated codes.

We will be able to cleanly manage the codes and maintenance procedure which will reduce the cost largely.

In contrast to the polling methodology, observer pattern gives a great advantage in performance wise, since observers won’t keep polling to see whether there are any new messages, but they are being notified until then. So observers will be idle until a real need arises. In a way observers can be seen as agents.

And much more …

Does java ship with Observer implementations?

Java implements Observer design pattern for some extent when using listeners to user interfaces.

Think you have a button in your UI and you want to perform different functionalities according to different ways users interact with it (E.g. – Button Clicked down, Button click up, Button click, etc.). Therefore users can connect different listeners to that button. These listeners act as observers observing the button. Any change to the button will be grabbed by the corresponding function.

Here users are allowed to attach any amount of listeners to the button which preserves the loose coupling of observer design pattern.

Following is a simple example how it works.

 
2 Comments

Posted by on September 12, 2012 in Design patterns, Java

 

Tags: , ,

Decorator Design Pattern


Decorator Design Pattern tutorial with design diagrams and code examples.

Overview

  • Background

  • Scenario

  • Design diagram of Decorator Pattern

  • Implementation

Background

Hi Guys it’s time to take down another mysterious design pattern called Decorator Pattern. As we already learned, Factory design pattern helps programmers to create new objects, whereas Decorator design pattern helps to extend existing objects. Yup that is the basic idea you have to keep in mind when designing software so when you come across such a situation you will remember the keyword “EXTEND” together with Decorator design pattern.

Scenario

Let’s think that we need to create a Car. But keep in mind the golden line “Make your code closed for modifications yet open for extensions”. OK, you will think no need to think big for this. Most of you will create your code as follows.

Figure1 – Car Class

OK, it’s pretty easily done and no worries. But few days later you will need to make the car better with a DVD player inside. So you will have to change this and probably come up with an answer like this.

Design diagram of Decorator Pattern

OK, that was pretty easy. But wait what about that golden line I was talking about? Yes you have opened the code for extension and performed extending the code but what about closed for modifications? You just modified your core code and that might be pretty costly in the long run. Well if there’s anybody who isn’t convinced yet. What if you need to improve the car more and more by introducing more and more features? You will continue to follow this same procedure? It won’t work. Code maintenance will be pretty hard and costly. So the solution for this kind of problem is to use the Decorator pattern.

And the use of decorator would be as follows;

Implementation

I hope now you can get a clear idea about how we are going to solve this matter. So let’s start coding.

As you can understand the core component, Car class, is pretty much the same. So we don’t need to change the Car class as shown in figure 1.

The rest of the classes (modifications) will be the decorators (E.g: RearCamera, DVDPLayer, etc) to this core Car class. And these classes should be kept under a common template. Therefore at the design level we as Software designers should provide abstract decorator class for programmers. Therefore they can create decorator classes to introduce more modifications by implementing the provided abstract decorator class.

However these decorator (wrapper) classes have to act as wrappers to the core component (Car). That means these wrappers should have a similar type to the core component (Car). Therefore we sub class the core component to create the abstract decorator (wrapper) class. It will be as follows.

Figure 4 – Abstract Decorator Class

Think how we should implement the Decorator classes. It’s obvious we have to sub class the abstract Decorator class. Here’s how the Decorator will work.

First we will be creating the core Car class.

Then, when a requirement arises to modify the car we need to wrap the Core class. While doing that we need to provide the Core class reference to the wrapper class right? Otherwise how will the new Decorator class decorate the previously created Car class? Therefore we should provide the Core class reference when creating the Decorator objects. Therefore the Decorators will follow the following standard.

Figure 5 – Concrete DVDPlayer Decorator Class

Figure 6 – Concrete RearCamera Decorator Class

Well that’s pretty much it. So let’s test that out.

Figure 7 – Testing the Decorator Design pattern

And the output is – 

So you can see that it solves the problem and if you need any further modifications to be done to the Car you just need to create a new Decorator class and use it at the run time as shown in the selected area in figure 7.

I will show how this worked out graphically referring to the code lines of figure 7.

So as you can see gradually we have added the layers and at the end we are having the core class wrapped with many modifications without affecting the core codes.

And when we call the car reference’s description method it will call its super class’s (DVD Player) and it will call its super class’s (Car) description method and they will be executed in reverse order and eventually all the description methods will be called one after other starting from inside to outside wrappers.   

 
1 Comment

Posted by on September 6, 2012 in Design patterns, Java

 

Tags: , ,

Insight of Strategy Design Pattern


Strategy Design Pattern tutorial with design diagrams and code examples.

Overview

o   Background

o   Scenario

o   Better Way (Solving problem using “has a” instead of “is a”)

o   Design diagram of strategy design pattern

Background

Have you ever thought what the better approach between composition and inheritance is? And if you were given the opportunity to design software using either of these two methods, I’m sure most of you will stuck to inheritance. This is because we can easily think of our software in a hierarchical manner. But is it the best way for our software? Does it really support better maintenance?

Most likely some of you may still be confused weather we can use inheritance and composition interchangeably because they are two different concepts.

Well you don’t need to worry, just continue this tutorial and you will end up by grasping lots of important knowledge about designing software.

Scenario

Think of a situation where you were asked to create a jungle. The most common approach would be to create an abstract Animal class with the intention of sub classing it to create other animals. (Note that Animal class is abstract because we don’t need anybody to instantiate Animal class. There are no Animal objects in real world).

Figure 1 – Abstract Animal Class

Then the rest of the Animal classes will be created by sub classing this Animal class as follows.

And we can create sub Classes as follows.

And we can refer to the Dog class as follows.

The output will result as “I’m Walking” as expected. And similarly other Classes will also provide the same result. And you are happy since that worked out pretty well.

But wait a minute. This just doesn’t seem to be right. This will result both Twitter’s and Goldfish’s go methods to output as I’m Walking which should be I’m Flying and I’m swimming respectively.

So what should we do to avoid this being happening? As most of you might have guessed we can override the go() method of both Twitter and Goldfish to provide their specific functions as follows.

Well now everything seems to be all right. J . What can go wrong!

WAIT! You haven’t solved anything instead messed everything up because you have thrown the code reuse (One of the most important factors to consider while designing software) out of the window.

In every level you just have to code special functionalities according to the requirements of the classes. Think when more and more animals come in to the Jungle you will have to code many different go() methods accordingly.

So what causes this problem and what is the possible answer? It just seem like there’s no answer to this problem because we have used the only possible answer. Actually not, we have to use composition over inheritance. Then the problem will be solved. Let’s consider that approach.

Better Way (Solving problem using “has a” instead of “is a”)

Can you recall the problem we had? It’s a very popular and unforgivable mistake that we have done. That is we were unable to separate the parts that tempt to change over time. We should separate those changeable parts from the rest of our application and reuse them as much as possible. That will result in an application  that supports easy maintenance.Keep in mind that we should keep those codes that tempt to change as freestanding as possible to avoid major code changes that will affect core code changes as well.

In this case inheritance is the worst because it will spread the changeable codes over generations allowing the programmers to change them over many generations. We have to override the methods to our specific needs and in the next level we will have to override that code again to assist that particular class.

Therefore the best way is to extract out the go method and provide “has a” relationship to the corresponding classes. In this scenario we found several special go() methods namely goBYWalking(), goBYFlying(), goBySwimming(). So we can extract all these specific go methods out and link. In order to perform this we can provide the programmers a template by allowing them to subclass a go() method always. This approach will force a constraint for programmers to stick to same template throughout the project life.

Therefore the architect can provide an interface with go() method to be inherited by programmers to create specific go() methods and link them with corresponding classes. Go interface is shown follows.

Figure 3 – Go Interface

And the specific go() methods will be created by implementing the interface as follows.

Figure 4 – Specific Go Class

And now we will have to use these specific go methods inside each animal object and we at the design level should impose the constraint to use these methods at the implementation level. We will do this by providing a revised Animal class to the programmer that they will use to create Specific Animal objects. Revised abstract Animal Class has presented below.

Figure 5 – Revised Animal Class

Here, programmer can define the appropriate go() method to the particular Class in its constructor so every object will get the same go() method accordingly.

Figure 6 – Revised Dog Class

Design diagram of strategy design pattern

Therefore the Strategy design pattern to this specific problem can be illustrated as follows.

 
2 Comments

Posted by on September 4, 2012 in Design patterns, Java

 

Tags: , ,

Advanced Factory method Design pattern


Factory Design Pattern tutorial with design diagrams and code examples.

Overview

  • Scenario.

  • Description of normal factory method.

  • Description of extended factory method.

  • Design diagram of extended factory method.

Scenario

Think of a situation where you are asked to create a TOYOTA car. So you will happily finish your work by using “new” keyword as follows.

public abstract class Car {

public Car() {
}
public abstract String description();
}

Then there would be another request to create a BENZ car. So you would repeat the same procedure as follows.

But the problem arises when we need to create a HONDA car. Then we may use the same method as follows.

But as we can see we have to repeat the same procedure when a new car has to be created and this cause to change our core code frequently as requirements arise. So a better approach would be to provide a separate method to create the objects since these object creations might repeat many times in our code.

public class CarCreation {

Car myCar;
public Car createCar(String type){

if(type.equals("toyota")){
myCar = new ToyotaCar();
}else if (type.equals("benz")) {
myCar = new BenzCar();
}else {
myCar = new HondaCar();
}
return myCar;
}
}

Description of normal factory method

Here we have factored our code to a method and by this it will close the core code for modifications while keeping only this method to be exposed for changes. However, the best method will be to create a factory object out of this to keep this changeable part out of the core code. Therefore the factory method would be as follows.

public class CarFactory {

protected String type;
private Car myCar;

public CarFactory(String t) {
type = t;
}

public Car createCar(){

if(type.equals("toyota")){
myCar = new ToyotaCar();
}else if (type.equals("benz")) {
myCar = new BenzCar();
}else {
myCar = new HondaCar();
}
return myCar;
}
}

And the factory will be addressed at the run time as follows to retrieve the appropriate object via passing out parameters to factory.

public static void main(String[] args) {
Car car;
CarFactory carFactory = new CarFactory("toyota");
car = carFactory.createCar();
car.description();
}

As you may have already noticed all the cars (TOYOTA, BENZ and HONDA) are of “Car” type. Therefore we can provide an abstract Car class to impose constrains to keep all car types under same constrains. Abstract Car class can be initialized as follows.

public abstract class Car {

public Car() {
}
public abstract String description();
}

Therefore the concrete Car classes will be forced to follow a common structure as follows.

public class ToyotaCar extends Car{

@Override
public String description() {
return "TOYOTA";
}
}

The described Factory method can be displayed as follows;

Description of extended factory method

Ok, Now we are done with the factory method and we are having a factory and abstract Car class which will be sub classed to produce various cars from the factory as requested by the user at run time.

But wait What if there is a different user who needs a specialized car like a bullet proof vehicle. It’s obvious we can’t use the same factory to produce different cars so we need to go for a different factory. But anybody can come up with different kinds of factories having different skeletons.

And Java comes with various factory objects. Following is an example.

try {
XMLReader myReader = XMLReaderFactory.createXMLReader();
} catch (SAXException e) {
System.err.println(e.getMessage());
}

Is this the way we should impose a programmer to continue? Definitely not, that’s why we should take the design for a higher level. Because main goals of design patterns are to allow the code for extendibility and closed for modifications. Therefore we may provide an abstract Factory Class while providing the programmer to build factories as their wish while imposing a skeleton to work with. And the abstract Class will look as follows.

public abstract class AbstractCarFactory {

public AbstractCarFactory() {

}
protected abstract Car createCar(String type);

}

So this extended factory design method will allow programmers extra layer to work with allowing the code for extensions.

public class extendedCarFactory extends AbstractCarFactory{

protected String type;
private Car myCar;

public extendedCarFactory() {}

@Override
protected Car createCar(String type) {
if(type.equals("toyota")){
myCar = new ToyotaCar();
}else if (type.equals("benz")) {
myCar = new BenzCar();
}else {
myCar = new HondaCar();
}
return myCar;
}
}

We will craft the architecture by providing the abstract classes indicated in red color with special methods as described earlier. And the programmer will be provided the capability to acquire different car objects using the factory they created by sub classing the provided abstract factory class.

Design diagram of extended factory method

 
2 Comments

Posted by on August 28, 2012 in Design patterns, Java

 

Tags: , ,

Singleton Design Pattern


Singleton Design Pattern tutorial with design diagrams and code examples.

——————————————————————————————————-

Overview

1.0 Introduction to singleton design pattern

2.0 Traditional implementation

3.0 Issues with the traditional approach

4.0 Solutions provided and advanced singleton method

——————————————————————————————————-

1.0 Introduction to singleton design pattern

In programming, have you ever come across with a situation where you need to allow users to deal with only one single object of a particular class?

And why we need to limit the number of objects to just one?

Think of a situation where we model a clipboard (Helps to keep temporary data, stores the contents of copied data of the computer) or a register. If there are possibilities for users to have multiple objects of clipboards (or register) then when we paste the copied things then it will have conflicts (in a normal computer).

So in day today programming we may have to come across these kind of situations where we need to allow only one object to be maintained at run time.  Singleton design pattern helps to do it for us.

2.0 Traditional implementation

What is the normal way of creating new objects in java?  It’s by using the new keyword.  So if users are able to use “new” keyword to create objects then they can always create as many objects as they need. So we should take control over that process by making the class’s constructor invisible for users. So they can’t use the keyword. Because we use new keyword to execute the constructor of class to generate objects out of it and if the constructor is not visible then we can’t create objects. [Line 6]

Since users can’t create objects now we should provide them the same object as per the requirement. And class should maintain it. It should create the object once and once only and if there are further requests for objects then it should return the same object created early. [Line 8 – 15]

Singleton Traditional approach

OK, now everything is done and users should use “getInstance()” method to retrieve the object and class will make sure only one object will be transferred to every request.

3.0 Issues with the traditional approach

What happens if this code residing in a multi-threaded application, and two threads requesting the object for the first time at the same time? Then class will check the line 10 and find out still there is no object created early (Since both threads requesting object for the first time) and will create object(Line 11) and return them. So if two threads are accessing the 10th line at the same time there will be two objects returned. So it destroys the whole concept.

4.0 Solutions provided and advanced singleton method

So the answer is to make the “getInstance()” method thread safe by introducing “synchronized” keyword.

But this will lead to a performance hit. Because synchronized method will let other threads to wait in a queue until one thread completes its execution. So the best thing is to reduce the synchronized code as much as possible.

So following code will address all these issues and provides a better solution.

public class Clipboard {

private static Clipboard singletonObject = new Clipboard();
private Clipboard(){}

public static synchronized Clipboard getInstance(){

return singletonObject;
}
}

Further important points regarding possible issues and alterations to Singleton can be found here.

 
1 Comment

Posted by on July 18, 2012 in Design patterns, Java

 

Tags: , ,

Introduction to design patterns


Why design patterns?

  • Have you ever felt that you have already come across a pattern when designing new software? You introduce a design by going through a painful process yet delivering the same design as in earlier times. So we keep re-inventing the wheel. Design patterns provide designs so our problem is already solved by experts we just need to adopt it.

What are the advantages of using them?

  • Design patterns help you to introduce the designs out of the box. So you don’t need to follow painful steps to introduce a design again, the designs you need are already being created you just need to select the appropriate one.
  • These designs are what experts suggest and they are highly maintainable and industry proven.
  • Design patterns are extensions to OOP. You remember the times we programed using procedural languages where you had to consider a process as set of steps. Then programming became easier with the introduction of OOP where we bundle set of steps under objects. Design patterns go beyond the objects concepts and bundles objects together and provide solutions.

What are the disadvantages?

There are no disadvantages as such but “some” design patterns might increase the complexity of simple software. So if the software does not grow and fairly simple, you can avoid the use of “some” design patterns.

So I will be discussing about most popular design patters that we can adopt in our day to day programming to make our lives easier and productive 🙂 So stay tuned !

 
Leave a comment

Posted by on July 16, 2012 in Design patterns, Java

 

Tags: ,

Image

Its About Us! :)


Hi guys,

This is the beginning of my blog and it will be majorly covered with technical stuff and also hoping to cover few interesting topics to simply refresh all of you guys.

As the title indicates, its about gaining in many ways as much as we can. So join with me and LETS GAIN!. And keep this flow open from both ends, since i am making my flow open and active hopefully you guys can contribute too.

Surely there are many to learn and gain so lets get started!

Lets Start!

Lets Start!

 
Leave a comment

Posted by on May 18, 2012 in Milestones

 
 
Create your own website, free on WordPress.com.Create your own website.
Start free