Tuesday, 21 May 2013

Flyweight Pattern Example - JAVA


Flyweight pattern is mainly used to reuse objects. This one of the structural pattern. We can understand this pattern by following example. Here we are using bikes with different type, color and cc.

1. Create interface as given below.
public interface Bike {
Bike getBike(String type);
void setColor(String color);
void setCc(int cc);
String getDetails();
}//Bike 

2. Create class HondaBike as given below.
public class HondaBike implements Bike {
private int cc;
private String color, type;

public HondaBike(String type) {
this.type = type;
}//HondaBike

public Bike getBike(String type) {
return new HondaBike(type);
}//getBike

public void setColor(String color) {
this.color = color;
}//setColor

public void setCc(int cc) {
this.cc = cc;
}//setCc

public String getDetails() {
return "\nColor : " + color + "\tCC : " + cc + "\tType : " + type;
}//getDetails
}//class HondaBike

3. Create BikeGenerator as given below.
import java.util.HashMap;

public class BikeGenerator {
private HashMap<String, Bike> bikeStore = new HashMap<>();
public Bike getBike(String type) {
Bike bike = (Bike) bikeStore.get(type);

if(bike == null) {
bikeStore.put(type, new HondaBike(type));
System.out.print("\nGenerating new bike object with type : " + type);
}//if
else {
System.out.print("\nReturning existing object.");
}//else
return (Bike)bikeStore.get(type);
}//getBike
}//BikeGenerator

4. Now we can create our main class as given below.
public class Main {
public static void main(String args[]) {
BikeGenerator bg = new BikeGenerator();

Bike hondaSimple = bg.getBike("simple");
hondaSimple.setColor("Red");
hondaSimple.setCc(100);
System.out.print("\n" + hondaSimple.getDetails());

Bike hondaDelux = bg.getBike("delux");
hondaDelux.setColor("Red");
hondaDelux.setCc(150);
System.out.print("\n" + hondaDelux.getDetails());

Bike  hondaGold = bg.getBike("gold");
hondaGold.setColor("Red");
hondaGold.setCc(350);
System.out.print("\n" + hondaGold.getDetails());

Bike hondaAgainSimple = bg.getBike("simple");
hondaAgainSimple.setColor("Black");
hondaAgainSimple.setCc(350);
System.out.print("\n" + hondaAgainSimple.getDetails());

}//PSVM
}//Main

And now you are ready to run example. Output will explain you waht we have achieved.

Monday, 20 May 2013

Facade Pattern Example


Facade pattern is one of the structural pattern which is used to hide internal complexity. Here I am giving one example of color filling. You can use following steps to get working example of facede pattern.

1. First create Color interface.
public interface Color {
void fillColor();
}//Color

2. Now create class Redcolor
public class RedColor implements Color {
public void fillColor() {
System.out.print("\nFilling red color");
}//fillColor
}//RedColor

3.Now create class BlueColor
public class BlueColor implements Color {
public void fillColor() {
System.out.print("\nFilling blue color");
}//fillColor
}//BlueColor

4. Now create class GreenColor
public class GreenColor implements Color {
public void fillColor() {
System.out.print("\nFilling green color");
}//fillColor
}//GreenColor

5. Here we go for creating ColorFiller class which is going to hide complexity.
public class ColorFiller {
private Color redColor;
private Color blueColor;
private Color greenColor;

public ColorFiller() {
redColor = new RedColor();
blueColor = new BlueColor();
greenColor = new GreenColor();
}//ColorFiller

public void fillRedColor() {
redColor.fillColor();
}//fillRedColor

public void fillBlueColor() {
blueColor.fillColor();
}//fillBlueColor

public void fillGreenColor() {
greenColor.fillColor();
}//fillGreenColor
}//CollerFiller

6. Here Main class where we have to use this pattern.
public class Main {
public static void main(String args[]) {
ColorFiller cf = new ColorFiller();
cf.fillRedColor();
cf.fillBlueColor();
cf.fillGreenColor();
}//PSVM
}//Main

Sunday, 19 May 2013

Composit Pattern Example

Composit design pattern is one of the structural pattern. You can use this pattern for maintaining hierarchy of objects. Here I am going to explain example with college staff hierarchy. You can follo steps to get working example.

1. Create StaffMember class as given below. Here remember that composit pattern class will always have list of objects of its own type.
import java.util.ArrayList;
import java.util.List;

public class StaffMember {
    private int ID;
    private String name, desg;
    public List<StaffMember> subMember;
   
    public StaffMember(int ID, String name, String desg) {
        this.ID = ID;
        this.name = name;
        this.desg = desg;
        subMember = new ArrayList<StaffMember>();
    }//StaffMember
   
    public void addSubMember(StaffMember staffMember) {
        subMember.add(staffMember);
    }//addSubMember
   
    public List<StaffMember> getSubMember(StaffMember staffMember) {
        return subMember;
    }//getSubMember
   
    public String toString() {
        return "\nID : " + ID + "\tName : " + name + "\tDesg : " + desg;
    }//toString
   
}//class StaffMember

2. Now create Main class for demo as given below.
import java.util.List;

public class Main {
    public static void main(String args[]) {
        StaffMember headMaster = new StaffMember(1, "A", "HeadMaster");
        StaffMember subHeadMaster = new StaffMember(2, "B", "Sub-HeadMaster");
        StaffMember supervisor1 = new StaffMember(3, "C", "Supervisor-1");
        StaffMember supervisor2 = new StaffMember(4, "D", "Supervisor-2");
        StaffMember teacher1 = new StaffMember(5, "E", "Teacher-1");
        StaffMember teacher2 = new StaffMember(6, "F", "Teacher-2");
        StaffMember teacher3 = new StaffMember(7, "G", "Teacher-3");
        StaffMember teacher4 = new StaffMember(8, "H", "Teacher-4");
        headMaster.addSubMember(subHeadMaster);
        subHeadMaster.addSubMember(supervisor1);
        subHeadMaster.addSubMember(supervisor2);
        supervisor1.addSubMember(teacher1);
        supervisor1.addSubMember(teacher2);
        supervisor2.addSubMember(teacher3);
        supervisor2.addSubMember(teacher4);
       
        System.out.print("\nHead master hierarchy : ");
        printHierarchy(headMaster);
        System.out.print("\n=========================================");
        System.out.print("\nSub head master hierarchy : ");
        printHierarchy(subHeadMaster);
        System.out.print("\n=========================================");
        System.out.print("\nSupervisor 1 hierarchy : ");
        printHierarchy(supervisor1);
        System.out.print("\n=========================================");
        System.out.print("\nSupervisor 2 hierarchy : ");
        printHierarchy(supervisor2);
       
    }//PSVM
   
    public static void printHierarchy(StaffMember staffMember) {
        System.out.print(staffMember.toString());
        List<StaffMember> member = staffMember.getSubMember(staffMember);
        for(int i = 0; i < member.size(); i++) {
            printHierarchy(member.get(i));
        }//for i
    }//printHierarchy
   
}//class Main

Now you modify StaffMember class for additional information like you can store parent of that object. You can put some checks when adding member. You can add method for removing member from hierarchy.

Friday, 17 May 2013

Filter Pattern Example - JAVA


Filter pattern is mainly used to filter group of objects based on some criteria  We can see one simple example of this filter pattern. Here we are going to filter laptops based on company and OS. Use following steps to build example.
1. Create class Laptops as given below.
public class Laptops {
String company, os;
int bits;
public Laptops(String company, String os, int bits) {
this.company = company;
this.os = os;
this.bits = bits;
}//Laptops
public String getCompany() { return company; }
public String getOs() { return os; }
public int getBits() { return bits; }
}//class Laptops

2. Create interface Filter as given below.
import java.util.List;
public interface Filter {
List<Laptops> filterObjects(List<Laptops> laptops);
}

3. Create class HclFilter as given below.
import java.util.ArrayList;
import java.util.List;
public class HclFilter implements Filter {
public List<Laptops> filterObjects(List<Laptops> laptops) {
List<Laptops> hclLaptops = new ArrayList<>();
for(int i = 0; i < laptops.size(); i++)
if(laptops.get(i).getCompany().equalsIgnoreCase("hcl"))
hclLaptops.add(laptops.get(i));
return hclLaptops;
}//filterObjects
}//HclFilter

4. Create class WindowsOsFilter as given below.
import java.util.ArrayList;
import java.util.List;
public class WindowsOsFilter implements Filter {
public List<Laptops> filterObjects(List<Laptops> laptops) {
List<Laptops> windowsOsLaptops = new ArrayList<>();
for(int i = 0; i < laptops.size(); i++)
if(laptops.get(i).getOs().equalsIgnoreCase("windows"))
windowsOsLaptops.add(laptops.get(i));
return windowsOsLaptops;
}//filterObjects
}//WindowsOsFilter

5. And now our demo class for filter pattern.
import java.util.ArrayList;
import java.util.List;
public class FilterDemo {
public static void main(String args[]) {
List<Laptops> allLaptops = new ArrayList<Laptops>();
allLaptops.add(new Laptops("hcl", "windows", 32)); allLaptops.add(new Laptops("hcl", "linux", 32));
allLaptops.add(new Laptops("hcl", "solaries", 64)); allLaptops.add(new Laptops("dell", "windows", 32));
allLaptops.add(new Laptops("dell", "linux", 32)); allLaptops.add(new Laptops("dell", "solaries", 64));
Filter hclLaptops = new HclFilter();
Filter windowsOsLaptops = new WindowsOsFilter();
List<Laptops> filteredLaptops = hclLaptops.filterObjects(allLaptops);
System.out.print("\nAll HCL laptops : ");
for(int i = 0; i < filteredLaptops.size(); i++)
System.out.print("\nCompany : " + filteredLaptops.get(i).getCompany() + "\tOs : " + filteredLaptops.get(i).getOs());
filteredLaptops = null;
filteredLaptops = windowsOsLaptops.filterObjects(allLaptops);
System.out.print("\nAll windows os laptops : ");
for(int i = 0; i < filteredLaptops.size(); i++)
System.out.print("\nCompany : " + filteredLaptops.get(i).getCompany() + "\tOs : " + filteredLaptops.get(i).getOs());
}//PSVM
}//class FilterDemo

You can add more filters and can add "AND" & "OR" filters as well.

Thursday, 16 May 2013

Adapter pattern example


Adapter pattern is one of the structural pattern which makes two incompatible interfaces to work together. Idea can be more clear with example. For implementing adapter pattern you can follow given steps.

Here example is of ColorProvider class. This ColorProvider class implements interface called BasicColors which can provide only red, green and blue colours. There is another interface called AdvancedColors whic provides yellow, pink, white and black colors. In this case adapter pattern will make BasicColors and AdvancedColors to work together without any changes in interface of ColorProvider class.

1. Create interface BasicColors as given below.
public interface BasicColors {
void getColor(String color);
}

2. Create interface AdvancedColors as given below.
public interface AdvancedColors {
void getColor();
}

3. Now we can create class ColorProvider which will be used by user.
public class ColorProvider implements BasicColors {
ColorAdapter colorAdapter;
public void getColor(String color) {
if(color.equalsIgnoreCase("red") || color.equalsIgnoreCase("green") || color.equalsIgnoreCase("blue")) {
System.out.print("\nBasic colour " + color + " by BasicColor interface.");
}//if
else {
colorAdapter = new ColorAdapter();
colorAdapter.getColor(color);
}//else
}//getColor
}//class ColorProvider

4. Here we go for ColorAdapter as given below.
public class ColorAdapter implements BasicColors {
AdvancedColors advColor;

public void getColor(String color) {
if(color.equalsIgnoreCase("yellow")) {
advColor = new Yellow();
advColor.getColor();
}//if
else if(color.equalsIgnoreCase("pink")) {
advColor = new Pink();
advColor.getColor();
}//else if
else if(color.equalsIgnoreCase("black")) {
advColor = new Black();
advColor.getColor();
}//else if
else if(color.equalsIgnoreCase("white")) {
advColor = new White();
advColor.getColor();
}//else if
}//getColor
}//class ColorAdapter

5. Now we can implement concreet classes of advanced colors as given below.
public class Yellow implements AdvancedColors {
public void getColor() {
System.out.print("\nAdvanced yellow color.");
}
}

public class Pink implements AdvancedColors {
public void getColor() {
System.out.print("\nAdvanced pink color.");
}
}

public class Black implements AdvancedColors {
public void getColor() {
System.out.print("\nAdvanced black color.");
}
}

public class White implements AdvancedColors {
public void getColor() {
System.out.print("\nAdvanced white color.");
}
}

6. Here we go for demo i.e. for Main class.
public class Main {
public static void main(String args[]) {
ColorProvider cp = new ColorProvider();
cp.getColor("red");
cp.getColor("yellow");
cp.getColor("green");
cp.getColor("pink");
}
}

You can draw UML diagram for better understanding.

Tuesday, 14 May 2013

Factory Design Pattern Example


Factory pattern is creational pattern which hides object creation logic from user. We can see one example of factory patter for clear understanding. To execute your factory pattern use following steps:-

1. Create interface called Car as given below. It will be common reference to all Car objects that we are going to create.
public interface Car {
void myCar();
}

2. Now create one concreet class called Bmw. This class will be implementing interface Car.
public class Bmw implements Car {
public void myCar() {
System.out.print("\nBmw is my car.");
}
}


3. Now create another concreet class called Tata. This class will be implementing interface Car.
public class Tata implements Car {
public void myCar() {
System.out.print("\nTata is my car.");
}
}


4. Now create one more class called Maruti. Thisclass will be implementing interface Car.
public class Maruti implements Car {
public void myCar() {
System.out.print("\nMaruti is my car.");
}
}

5. Now you have to create one more class called CarFactory as given below. 
public class CarFactory {
public Car getCar(String carName) {
if(carName.equalsIgnoreCase("Tata"))
return new Tata();
else if(carName.equalsIgnoreCase("Maruti"))
return new Maruti();
else if(carName.equalsIgnoreCase("Bmw"))
return new Bmw();
return null;
}
}


6. Now our pattern is ready. Let's write one class to implement this pattern.
public class CarShop {
public static void main(String args[]) {
CarFactory cf = new CarFactory();
Car c1 = cf.getCar("Tata");
c1.myCar();

c1 = cf.getCar("Maruti");
c1.myCar();
}
}

Here you are ready to execute your application.

Now you can see that if you want to add one more car to shop you just need to add one more class implementing Car interface and you are done. In this was this pattern provides flexibility and hides creational logic from user.

Monday, 13 May 2013

Thread class - JAVA


Thread class is present in java.lang package. This class implements Runnable interface. This class allows user to create multiple threads in application. These threads can execute code in concurrent way. Every thread 
is having some priority between 1 to 10. By default it set to 5. Every thead can create another thread. The priority of newly created thread is same as that of parent thread, but you can change this mannually. Thread 
can be daemon thread so new thread created by daemon will be daemon thread. 
We can create thread by extendding class Thread or by implementing Runnable interface. Best way is to implement Runnable interface because it will allow your class to extend another class so it will be flexible 
architecture.
Here is example by extending thread class,

class ThreadClass extends Thread {
public void run() {
try {
System.out.println("In run : 1");
Thread.sleep(2000);
System.out.println("In run : 2");
} catch(Exception e) { 
System.out.print("Exception : " + e);
}
}
public static void main(String args[]) {
ThreadClass tc = new ThreadClass();
tc.start();
}
}


And here is example by implementing runnable interface,

class ThreadClass implements Runnable {
private Thread th;
public ThreadClass() {
th= new Thread(this);
th.start();
}
public void run() {
try {
System.out.println("In run : 1");
Thread.sleep(2000);
System.out.println("In run : 2");
} catch(Exception e) { 
System.out.print("Exception : " + e);
}
}
public static void main(String args[]) {
ThreadClass tc = new ThreadClass();
}
}


Here you can see that class extending Thread class is not having any chance to extends any class but class implementing Runnable is having that chance.

Thread class is having many constructors like given below,
Thread();
Thread(String name);
Thread(ThreadGroup group, String name);
Thread(Runnable target, String name);
Thread(ThreadGroup group, Runnable target, String name);
Thread(ThreadGroup group, Runnable target, String name, long stackSize);
Every constructor internally calls init method of Thread class which is described below.

Thread class gives start() method which is synchronised by nature and you can't restart any thread which has completed its execution or you can't call start() method more than onse on same thread otherwise it will throw
IllegalThreadStateException. This start method calls another start0() native method. 

stop() method stops the execution of thread. In this method SecurityManager comes into picture. For stoping thread help of ThreadDeath class which is subclass of Error class is taken.

Thread.currentThread() method returns reference to current thread. Onse you are getting reference to current thread you can perform different operations on it.

Thread.sleep(timeInMilliSec) This method makes thread to sleep for given time.

Thread.sleep(milliSec, nanoSec) This makes thread to sleep for given milli seconds and nano seconds.

Thread.init(group, target, name, stackSize); This method initializes thread where group is the thread group, target is the target object whose run method we have to execute, name of thread an stack size for thread.
Other properties like priority, daemon or not will be copied from parent thread or you can set then mannually.

Thread.yield() method makes current thread to pause temporarly and allows other threads to run.

interrupt() method interrupts thread. This methos calls interrupt0() native method internally.

isInterrupted() method tells you whether given thread is interrupted or not.

isAlive() method returns boolean value stating whether thread is alive or not.

setPriority() method sets priority of thread. This priority can be between 1 to 10 where 1 is lower priority and 10 is higher priority.

activeCount() returns number of active threads in current thread group.

join(), join(milliSec), join(milliSec, nanoSec) waits for thread to die.

setDaemon(boolean), isDaemon() are methods related with daemon threads.

Along with these methods Thread class gives other methods like suspend(), resume() etc.

Enumerations - JAVA


We can make use of enumerations, when we need some constant values. Example is in coffee shop we may have only three types of coffee mugs like small, medium and large. In such a situation enumeration will reduce the possibility of errors. Let's see how to use enumerations in our code.

There are some rules that you have to follow while using enumerations.
1. Enumerations can be defined outside of class but with public access modifier only (It may be without access modifier i.e. default access).
2. You can define enumerations inside class with public, private, protected and static modifires only. 
3. You can't define enumerations in methods.
Now let's see example of this,

enum Outer {
SMALL, MID, LARGE
}//enum Size
class MainClass {
enum Inner {
SMALL, MID, LARGE
}//enum Size

public static void main(String args[]) {
System.out.print("\nOuter enum : " + Outer.LARGE + "\nInner enum : " + Inner.LARGE);
}//PSVM
}//MainClass

Now we can continue looking more features of enumerations,
4. You can place constructors in enum class and can overload those constructors.
5. You can have variables in enum class.
6. You can have getter and setter methods in enum class
Let's see example of this,
enum Outer{
SMALL(8), MID(10), LARGE(15);
private int value;
private Outer(int value) {
this.value = value;
}//Outer
public int getValue() {
return value;
}
}//enum Outer

class MainClass {
enum Inner {
SMALL, MID, LARGE
}//enum Size

public static void main(String args[]) {
System.out.print("\nOuter enum : " + Outer.LARGE.getValue() + "\nInner enum : " + Inner.LARGE);
}//PSVM
}//MainClass

Another important thing is that you can't place enums in static block. They can be placed only in top level class, interface or outside of everything i.e. as independent  But you can place enum in static inner class. Here is example of that,
class MainClass {
static class InnerClass {
enum Inner
{
SMALL, MID, LARGE
}//enum Size
}

public static void main(String args[]) {
System.out.print("\nInner enum : " + InnerClass.Inner.LARGE);
}//PSVM
}//MainClass
Even following peace of code is valid,
interface OuterInterface {
enum OuterEnum {
SMALL
}//OuterEnum
static interface InnerInterface {
enum InnerEnum {
SMALL
}//InnerEnum
}//InnerInterface
}//OuterInterface
You can explore this with all combinations.

Friday, 10 May 2013

System class 2 - JAVA

Continue from http://tech-world-brij.blogspot.in/2013/05/system-class-1-java.html
Another interesting method of System class is System.getProperty. It gives much useful information about java, current use and OS. Here is example,

class SystemClass
{
public static void main(String[] args) 
{
System.out.print("\n" + System.getProperty("java.version"));
System.out.print("\n" + System.getProperty("java.vendor"));
System.out.print("\n" + System.getProperty("java.vendor.url"));
System.out.print("\n" + System.getProperty("java.home"));
System.out.print("\n" + System.getProperty("java.class.version"));
System.out.print("\n" + System.getProperty("java.class.path"));
System.out.print("\n" + System.getProperty("os.name"));
System.out.print("\n" + System.getProperty("os.arch"));
System.out.print("\n" + System.getProperty("os.version"));
System.out.print("\n" + System.getProperty("line.separator"));
System.out.print("\n" + System.getProperty("user.name"));
System.out.print("\n" + System.getProperty("user.home"));
System.out.print("\n" + System.getProperty("user.dirr"));
System.out.print("\n" + System.getProperty("file.separator"));
}
}

If you are in need of more information then use System.getProperties().

System.exit(int); method will exit from currently running program directly.

System.gc() can be called to make space i.e. it will free all unused memory. This method internally calls Runtime.getRunTime().gc();

System.currentTimeMillis() and System.nanoTime() these functions will give you current system time in milli-seconds and nano-seconds respectively.

System.getenv("ENV_VAR_NAME") this method will return you value of that specific environment variable.

System.getenv() this method will return all environment variables and path of system. It will also give processor architecture, number of processors, home drive etc. If you exactly know what you want then use above method.

System class 1 - JAVA


This is one of the useful class in java which is present in java.lang package. We can't instantiate this class manually means we can't create object of this class but still this class is having empty constructor. You can't 
create sub-class of System class because it is final by nature. This class gives us in, out and err streams. All these three streams are public static and final by nature. These streams are public so that you can 
access them from outside of System class, static so that you can access them without creating object of System class and final for avoiding overriding of these streams. These streams are already open and are ready to 
process data. Let's take a look at each one of these.

1. System.in:-
This is of type InputStream. This is connected to keyboard by default but we can redirect this to some other input device. InputStream class is from java.io package and abstract by nature. InputStream class is superclass of all byte oriented input streams. This class is not having any constructor.

2. System.out:-
This is of type PrintStream. This is connected to monirot by default but we can redirect this to some other output device. PrintStream class is from java.io package. This class is having many different constructors. 

3. System.err:-
This is of type PrintStream. This is connected to monitor by default but we can redirect to some other output device.

Now lets see one example of redirecting stream to some other resource. In below example we are redirecting out stream to file.

import java.io.*;
class SystemClass
{
public static void main(String[] args) throws Exception
{
File f = new File("c:\\java\\test.txt");
PrintStream fout = new PrintStream(f);
System.setOut(fout);
System.out.print("This is test."); // This output will be written in test.txt file.
}
}
In this way you can play wilth other streams.


Another important facility provided by System class is System.arraycopy() function. This is native function in System class which is static by nature so you can use it directly. This function will perform faster than our
normal array copy logic. Here is one simple example of arraycopy function.

class SystemClass
{
public static void main(String[] args) 
{
int srcAry[] = new int[10];
int destAry[] = new int[10];
for(int i = 0; i < 10; i++)
{
srcAry[i] = i;
destAry[i] = -1;
System.out.print("\nSrc : " + srcAry[i] + "  :::  destAry : " + destAry[i]);
}
System.arraycopy(srcAry, 0, destAry, 0, 4);

System.out.print("\n\n\n\n\n");
for(int i = 0; i < 10; i++)
{
System.out.print("\nSrc : " + srcAry[i] + "  :::  destAry : " + destAry[i]);
}
}
}
System class provides another native method called System.identityHashCode(). This is static method. It will return same hash code for one program execution for one object.
You can continue reading here,
 http://tech-world-brij.blogspot.in/2013/05/system-class-2-java.html