Friday, 10 October 2014

How To...




Have you ever wondered what is behind the minds of successful people?
Not all people can become successful. Have you ever wondered why? Because successful people are often selfless.  Generally people always wanted to get richer. The person who wants to get rich only for him may become a robber, Person thinking of his wife and children only may end up in a monthly income job. But the one who can thinks of wider audience or one who thinks, “How can I make other people’s life better?” will become successful. The Whole world is part of their life too.
For example Bill Gates, why he has to become successful? He might have thought how can I make everybody can use computer. Life would be much easier if everyone knows how to operate the computer. (Do you remember even computing people struggled in command prompt). Another example I can give is, William Shakespeare who use to write plays and dramas thinking how I can entertain people. (Rather than how can I entertain my family or friends or myself). He had his own friends who can act in dramas that helped him to attract more audience. He might have thought “I think I should write these words for my friend... (Who ever he is) that would be really funny. People would laugh their guts out if it comes from him.... (Who ever he is).  I can give lot more examples in history like Marie Curie, Albert Einstein, Thomas Alva Edison all thought how do I make world a better place? People who have ability to share always get more.
We hear about Jihadist, Sometimes I wondered what they want to prove here.  Do they want to free people? (By sending all of them to heaven) or my life is a mess I would like to see everybody Else's life in a mess too. Some wanted to spread Ebola by contaminating themselves with the virus? Seriously? Not everybody can do that, you have to be strong for proving something. I caught 2 days of flue, and then I thought nobody should get this, even my enemies. I couldn’t sleep for two days with cough and fever and blocked nose. No, I would not wish this would happen to even recruiting people. (:)).
So if you want to become successful, be selfless and be strong and be willing to take risk for good cause. A fool, (who harm themselves and others) or a selfish cannot become successful. 
(forgive me for any grammatical errors or spelling mistakes , I am still learning English)

How To become Successful.

Friday, 28 February 2014

How To...

Proxy Pattern:
Provides a surrogate or placeholder for another object to control access to it. "Proxy" is actually a repesentative of another object.
A "remote Proxy" controls access to a remote object.
A "virtual Proxy" controls access to a resource that expensive to create.
A "protection Proxy" controls access to a resourse based on access rights.(security)
In this blog I am going to explain first one . This involves RMI ie Remote Method Invocation. This is the one topic in Java , I couldn't get to see, or touch.  Again all information here are referenced from Head First Design Patterns Book.
Image is taken from http://www.oodesign.com/proxy-pattern.html

Suppose client wants to call some methods on a object which is in Server's heap. Server is remote to the client and it has to talk to the server which is on the other side of  the network. RMI stub  act as a client proxy on the client's heap , where as RMI Skeleton act as server proxy on the Server's heap. Mainly these proxies help in serialization (write object in server side, readobject in client side-deserializing, This is before java 2. Now a days we can get proxies dynamically on the go. - just note that Proxies are  different pattern from decorator patterns.)
This needs two sides programming
 1) Client  side program or code  which lookup the RMI registry to get the stub object ,client invokes the method on the stub object, as if the stub is the real service.
       MyInterface service = (MyInterface)Naming.lookup("rmi://127.0.0.1/RemoteHelloworld");
2)Server side programming to give service.
           5 steps for these.
    i) Make a  Remote interface
            a)Extend java.rmi.Remote
              b)Declare that all methods throw a RemoteException.
               c)be sure arguments and return values are primitives or Serializable.
              import java.rmi.*;
                public interface MyRemoteInterface extends Remote {
                  public String helloWorld () throws RemoteException;
                 }
           ii)Make a Remote implementation
                a)Implement the Remote interface
                  b)Extend UnicastRemoteObject
                   c)Write a no-org constructor that declares a RemoteException
                   d)Register Service with the RMI registry
              public class MyImplementation extends UnicastRemoteObject implements MyRemoteInterface {
   public MyImplementation() throws RemoteException {}
      public String helloWorld() {
           return "hello world";
}
//more code
}
In tester in the main method you register the service with the RMI registry
  try {
MyInterface service = new MyImplementation();
Naming.rebind("RemoteHelloworld",service); //  you can give any name to hide your object.
} catch (Exception ex){....}
iii) generate stubs and skeletons
        run rmic on the remote implementation class (not on remote interface)
           %rmic MyImplementation
  iv)run rmiregistry
        bring up a terminal and start the rmiregistry
     %rmiregistry
v)start the service
        bring up another terminal and start your service
%java MyImplementation
 (run the main method of service impementation class)
Suppose I am a client wants to monitor some dogs at remote service. Then,
 First on the server side, we have to make the service available.
To make remote interface:
     import java rmi.*;
    public interface DogRemote extends Remote {
        public int getMicroChipNo() throws RemoteException;
        public String getSpecies() throws RemoteException;
         public String getLocation() throws RemoteExcetion;
         public String getCondition() throws RemoteExeption;
}
If you want to make a method like
public Collar getCollar() throws RemoteException; then you have to make "Collar " Serializable.  Just you can do public class Collar implements Serializable  or extends serializable .(there is no methods to implement).But you have to import java.io.*;   If the class contains any other objects you can make them serializable or declare it as transient.
make remote implementation
import java.rmi.*;
import java.rmi.server.*;
public class Dog extends UnicastRemoteObject implements DogRemote
//instance variable here
public Dog(String location,String species,int microchipno) throws RemoteException{
//code here
}
public int getMicroChipNo() {
    return microchipno;
}
public String getSpecies(){
return species;
}
// all other get codes here
}
Registering with RMI registry
public class DogTester {
   public static void main(String[] args){//you can also input arguments here.
try {
DogRemote pudsy = new Dog("London","poodle", 1234);
Naming.rebind("//"+"London.dogcanal.com" + "/dog",pudsy);/**here you can add differnt locations and different names for objects by passing args if you want.**/
}catch (Exception e){
e.printStackTrace();
}
}
}
Then run rmiregistry followed by the main method of DogTester.
On the client side,
Class to monitor dog and a tester
import java.rmi.*
public class DogMonitor{
  DogRemote pudsy;
public DogMonitor (DogRemote pudsy){
this.pudsy = pudsy;
}
public void dogDetails(){
try
{
      System.out.println("Dog from"+pudsy.getLocation());
     System.out.println("Dog Species"+pudsy.getSpecies());
      System.out.println("Condition"+pudsy.getCondition());
      System.out.println("Microchip number"+getMicroChipNo());
}  catch (RemoteException e){
e.printStackTrace();
     }
   }
}
Write a monitor tester
      import java.rmi.*;
     public class DogMonitorTester{
            public static void main(String[] args){
                  try
                     {
                          DogRemote  pudsy = (DogRemote)Naming.lookup("rmi://London.dogcanal.com/dog");
                          DogMonitor monitor = new DogMonitor(pudsy);
                            }
                              catch (Exception e){
                                    e.printStackTrace();
                             }
                         }
                          monitor.dogDetails();
}
}

       How to monitor dogs( or objects) remotely.             

Comments are welcome. (So that I can correct my mistakes)

Tuesday, 11 February 2014

How To...

Singleton Pattern:
"Ensures a class has only one instance, and provides a global point of access to it."
Here we are making a class , which has only one instance which is instanciated within itself and we never let any other class to make another instance.
we are providing a global access point to the instance. - Head first design pattern.
ex: servelets.
This picture is taken from  http://www.oodesign.com/singleton-pattern.html.

When restricting access , we always have to think about make something a "private". The method which instanciates object is the constructor. So we make constructor "private". When constuctor made private, it should be instanciated in a static method/variable so as to give global access. When you think of global access , make it thread safe.
public class Singleton{
private static Singleton uniqueInstance;
private Singleton(){}
public static synchronized Singleton getInstance() {
if (uniqueInstance == null) {
uniqueInstance = new Singleton();
}
return uniqueInstance;
}
}
To improve Multitreading
1) Do nothing if the performance of getInstance() is not critical
2)If your application always creates and uses singleton then create Singleton eagerly as JVM creates it when the class is loaded.
       public class Singleton {
          private static Singleton uniqueInstance = new Singleton();
      private Singleton(){}
    public static Singleton getInstance() {
        return uniqueInstance;
    JVM ensures that instance will be created before any thread can access to the static instance variable.
3)Use double-checked locking to reduce the use of sychronization in getInstance() - synchronization kills performance
public class Singleton{
   private volatile static Singleton uniqueInstance;
private Singleton(){}
public static Singleton getInstance(){
if (uniqueInstance == null){  /** only enter the block if it is null. this means it enters synchronized block only once for the first time.**/
synchronized (Singleton.class){
if (uniqueInstance == null)   /** double checking just in case first one checked by  two threads simultaniously  as one of them will succeeds,  other one waits just outside after first checking.**/
   uniqueInstance = new Singleton();
}
}
return uniqueInstance;
}
}
These are all referenced from "Head First Design Patterns" Since I do not want to mess  up with singleton pattern.
Time for our own Singletons. Let us think of Central heating System , and house as a class loader.(one singleton per one class loader). It has only one instance and anybody in the house can have access to it (global) .
I create them eagerly since I bought my house in the winter.(just kidding)

public class HeatingSystem {
private static HeatingSystem uniqueInstance = new HeatingSystem();
private static Temperature ;
//currentTime == calender.getTime();
private HeatingSystem(){}
public static HeatingSystem getInstance(){
return uniqueInstance;
}
public void setTimer(Time startTime, Time endTime){
        if (currentTime.equalsTo( startTime))
            onSystem();
       else if (currentTime .equalsTo(endTime))
            offSystem();
/** to get current time you can use
Calendar calender = Calendar.getInstance();
CurrentTime = calender.getTime();**/

}
public  void setTemp(Temperature temp)
{
        this.Temperature = temp;
}
public void onSytem(){
    // press the button
}
public void offSystem(){
//undo the pressed button
}
}
Now everybody has only one instance , and has global access to that instance. Husband gets the instance switch on the system, He forgets all about it and when he sees the gas bill he could  blame it on the wife since she had the same instance  and access, so he expected her to switched it off as it is her responsibility too.

How to fight over your Gas Bill. (All  characters here are fictitious , if it resembles someone or some incidents then it is purely coincidental).


Friday, 7 February 2014

How To....

The Command Pattern:
"Encapsulates a request as an object, thereby letting you parameterise other objects with different requests queue or log requests and support undoable operations."
It supports the decoupling of the invoker of a request and receiver of the request.
-Head First Design Patterns.
ex: Home automation systems,  ... or where ever you have to press the bottons then think of you as a client and the webpage which holds the button as innocent invoker(he is not responsible for all unexpected actions :))


 This Picture is from:
http://www.oodesign.com/command-pattern.html
 I remembered my dissertation in MSc. Jobs come to the server in a queue, and these jobs are discarded once they are done with it. 
Let us think about Briton got talent.  Let us say "ITV"  is our client. Ant&Deck are (is) our invoker/s. All vendors have different kinds of act to show. Our commands are performing acts.  This is the audition taking place some where in Birmingham  and it is a all day process and people can come anytime between 9am - 5pm and put thier name in the list carried by our invoker (Ant&Deck).  They have nothing to do with who is doing the act. They just have to announce thier name  according to the list and all acts are come as a surprise. Simon Cowell , Alesha Dixon ... undo button invokers.
public interface PerformingAct{
public void perform();
}
public class SingingAct implements PerformingAct{
Team team;
public SingingAct(Team team){
this.team =team;
}
public void perform(){
team.sing();
}
public class StopSingingAct impements PerformingAct{
Team team;
public StopSingingAct(Team team){
this.team =team;
}
public void perform(){
team.retreat();
}
}
Same way we can implement DancingAct, MimingAct,ScreamingAct....and stoping all those acts in a class.
This is our invoker.
public class Invoker{
ArrayList acts;//you can also use a LinkedList or a Queue.
   static PerformingAct stopact;
static int count ==0 ;
public Invoker(){
acts =  new ArrayList();// all invoker may have a list for marking purposes.
}

public void addAct(PerformingAct act){
acts.add(act);
}
public void announce(PerformingAct act){

setStopAct(act);
//check the size of the arraylist here
  PerformingAct act1 = (PerformingAct)acts.remove(0);
act1.perform();
}
public void xbottunPushed(){
count = count+1;
if( count >=2){
stopact.perform();
count ==0;
}
}
public void setStopAct(PerformingAct act){
stopact = act;
}
}
On the day of audition,
public class LoadPerformingActs{
public static void main(String[] args){
Invoker antdeck = new Invoker();
Invoker simon = new Invoker();
Invoker alesha = new Invoker();

Team teamA = new Team();
Team teamB = new Team();
PerformingAct diversity = new DancingAct(teamA);
PerformingAct stopDiversity = new StopDancingAct(teamA);
PerformingAct mindBlowing = new SingingAct(teamB);
PerformingAct stopMindBlowing = new StopSingingAct(teamB);
antdeck.add(diversity);
antdeck.add(mindBlowing);
antdeck.announce(stopDiversity);
simon.xbottonPushed();//this needs thread synchronization
alesha.xbottonPushed();/**this needs thread synchronization in real life. Here we assume that alesha and simon does not push the button at the same time.
.......
continues until 5 pm. **/
}
}
Just have to remember if  you make a class for commands they can be set in a queue and invokers only remember to execute the commands and  all actions are vendors' responsibility. 
  In this way commands helps  Invokers to detach themselves from responsibilities.

How to detach yourself from responsibilities. :>)


Tuesday, 28 January 2014

How To....

The Template Method Pattern :
"Defines the skeleton of an algorithm in a method,defering some steps to subclasses.Template Method lets subclasses redefine certain steps of an algorithm without changing the algorithm's structure"
Principle used : The Hollywood Principle i.e "Don't call us,we'll call you" (ha ha "never")
Here High level components determine "when"  lower level components are needed and how they are used, but  letting low level components to hook themselves into the system.
- head first design patterns book.
http://www.oodesign.com/template-pattern.html
Couple of months back I was annoyed by the dailymail article about how men look at  women.
For your information this is the article.
What are you staring at? Scientists reveal how our brain sees men as people, but women as body parts (and it's not just men who do it)

Read more: http://www.dailymail.co.uk/sciencetech/article-2179164/Double-vision-How-brains-men-people-women-body-parts.html#ixzz2rgMM8Kr7.
Let us think of a project for the men to create perfect woman.Let  "PerfectWoman" is an abstract class.
GarysPerfectWoman, PetersPerfectWoman are two concreate implementations.
public abstract class PerfectWoman{
// here you have some stuff to do. you need a media tackers,a graphic,a canvas ...., I only give general ideas it is not the full implementation

final void drawPerfectWomanImage(){

    drawHeadImage();
      drawUpperBodyImage();
     drawLowerBodyImage();
      drawLegImage();
      drawString();//this is the hook which does nothing.
}
      abstract void drawUpperBodyImage();
      abstract void drawLowerBodyImage();
  final void drawHeadImage(){
      g. setImage("kimkardashianheadImage.jpg" ,20.00,20.00,c);/** you never know whose head in that jpg**/
}
   final void drawLegImage(){
    g. setImage("JenniferLopezLeg.jpg",20.0,400.00,c);/** but you never know whose legs are  in that jpg**/
}
    void drawString(){}/** does nothing here , you can name your own name or you can leave this as it is.**/
}
Concreate implementation:
public class GarysPerfectWoman extends PerfectWoman{
// constructors not shown
public void drawUpperBodyImage(){
g.setImage("kieraknightlyUpperbodyimage.jpg",20.0,100.0,c);/** like this you can set your own picture.**/
}
public void drawLowerBodyImage(){
   g.setImage("jenniferLopezLowerBodyImage.jpg",20.0,200.0,c);
}
}
now some where in the tester
  PerfectWoman garys = new GarysPerfectWoman();
     garys. drawPerfectWomanImage();/** that draws a perfect woman for Gary , but Gary cannot change the head or leg.(we never let Gary to hurt  the feelings of good women)**/
In this way high level components controls the flow of the program and holds some control over some parts of the program.

title:

How to  draw image of a perfect woman without photoshop but with some guidelines.


Wednesday, 22 January 2014

How To....

The Observer Pattern:
"defines a one-to- many dependency between objects so that when one object change state ,all of its dependents are notified and updated automatically"
Design Priciple used:Strive for loosely coupled designs between objects that interact.
- Head first Design Patterns
The above picture is taken from http://www.oodesign.com/observer-pattern.html

Now is the time to understand life of a celebrity,let us say Wendy. Way back then ,when she wasn't a celebrity, she had only 3 friends. Susy, Loosy(she won't mind if I spelt her name wrong), Jenny. If she had something to say to them she knows how to say to them. Since for Susy, she just have to email her since she works in a office and mobile phone  is not allowed in there. (Her boss is too bossy). For Loosy , she had to text her since she is always outgoing and very busy. For Jenny she has to ring home since she is a house wife. (never checks email or mobile phones).
so if she has to give any updates she has to do
susy.email();
loosy.text();
jenny.ring();
Now she is a celebrity ie she is a subject so that everybody wants to hear her updates. She do not know everyone and she is busy to give everyone her updates. Now what should she do? I think she has to do a "Twitter" account. Everyone who wants to follow her (that is our observers) have to have some common methods so that she doesn't have to know everybody and thier needs. Let us consider one to many relationships and how to make class loosely coupled.Note that this is not our actual real life twitter.(a sort of)
Let us consider "Twitter" is our subject interface(it could be abstract also). Let us say "Follower" is our observer. There might be another interface "Communicator" depending on the needs.
public interface Twitter{
public void follow(Follower fl);
public void removeFollwer(Follower fl);
public void acknowledgeFollowers();
}
public interface Follower{
public void updateStatus(String tweet);
}
public interface Communicator{
public void communicate();
}

public class CelebrityTwitter implements Twitter {
     private ArrayList followers;
      private string tweet;
public CelebrityTwitter() {
    followers = new ArrayList();
}
public void follow(Follower fl){
       followers.add(fl);
}
public void removeFollower(Follower fl){
int k = followers.index(fl);
if (k>=0)
followers.remove(k);
}
public void acknowledgeFollowers(){
for (int i=0;i<observers.size();i++){
Follower follower = (Follower)followers.get(i);
follower.updateStatus(tweet);
}
public void setTweet(String tweet){
this.tweet =tweet;
acknowledgeFollowers();
}
}
Concreate implementation of Follower and Communicator
public class EmailCommunicator implements Follower,Communicator{
private string  tweet;
private Email email;
private Twitter  celebrityTwitter;
public EmailCommunicator(Twitter celebrityTwitter,Email email){
this.celebrityTwitter = celebrityTwitter;
this.email =email;
celebrityTwitter.follow(this);
}
public void updateStatus(String tweet){
this.tweet = tweet;
communicate();
}
public void communicate(){
email.send(tweet);
//phonenumber.sendText(); in case of TextCommunicator()
/**by the way this is not the way you actually send email. for that you have to import all these(
import java.util.*;
import javax.mail.*;
import javax.mail.internet.*;
import javax.activation.*;
and do some more stuff ) **/
}
}
Same way you can have lots of comunicator and Follower combinations.TextCommunicator,VoiceMailCommunicator..... all implement  "Follower" and "Communicator"  with different way of communications in communicate() method.
public class TwitterProfile{
public static void main(String[] args){
Twitter wendyTwitter = new CelebrityTwitter();
Email susyEmail = new Email("susy@email.com");
EmailCommunicator susycommunicator = new EmailCommunicator(wendyTwitter,susyEmail);
..........
TextCommunicator loosyCommunicator = new TextCommunicator(wendyTwitter, loosyphone);
.........
wendyTwitter.setTweet(" I am working on a film");
wendyTwitter.setTweet("I am going home from film  shooting");
........
Now everyone is Happy.   Wendy doesn't have to know everyone, as long as you follow her you get her tweeting updates as you desired.

Hence the title:

How To follow a celebrity without stalking.


Friday, 17 January 2014

How to ......

Strategy Pattern:
"Defines a family of algorithms, encapsulates each one,and makes them interchangeable.Strategy lets the algorithm vary independently from clients that use it."
OO principles used:
1) Encapsulate what varies.
2)Favor composition over inheritence.
3)Program to interfaces, not implementations.
- Head first Design patterns.
When you  hear the word "strategy" , always think of money or money making strategies. After you reading this blog I can assure you that you will never , never forget what is strategy pattern in OO designing.

 The above picture is from http://www.oodesign.com/strategy-pattern.html
Now let us consider a  topic that you all love. Let us consider cricket Players.Let " CricketPlayer" is an abstract class.  Bowler,Batsman,WicketKeeper ... are all concreate implementation of "CricketPlayer" Class. BowlingStrategy, BattingStrategy.... are interfaces.Now  GoodBattingStrategy, BadBattingStrategy,ModerateBattingStrategy are concreate implementations of BattingStrategies. Where as BadBowlingStrategy, GoodBowlingStrategy,ModerateBowlingStrategy are concreate implementations of BowlingStrategies.Oh ya, now what?  ah ha  "Now we can do some match fixing". (according to the money).We can fix the match even  on the spot.
public abstrct class CricketPlayer {
BattingStrategy battingstrategy;
BowlingStrategy bowlingstrategy;
public abstract void description();
public void setBowlingStrategy(BowlingStrategy bw){
     bowlingstrategy = bw;
}
public void setBattingStrategy(BattingStrategy bs){
      battingstrategy = bs;
}
public void doBatting(){
       battingstrategy.doBattingWithStrategy();
}
public void doBowling(){
        bowlingStrategy.doBowlingWithStrategy();
}
public void doFielding(){
System.out.println("everybody can do fielding");
}
// add some more methods if you want to.
  }
Now concreate implemetation of "CricketPlayer"
public class Batsman extends CricketPlayer {
public Batsman(){
      battingStrategy = new GoodBattingStategy();
      bowlingStategy = new BadBowlingStrategy();
}
puplic void description(){
System.out.println("normally I do good batting , but I can't do bowling");
}
// you can set wicket keeping strategy too
}
Now concreate implemetation of "CricketPlayer"
public class Bowler extends CricketPlayer {
public Bowler(){
      battingStrategy = new BadBattingStategy();
      bowlingStategy = new goodBowlingStrategy();
}
puplic void description(){
System.out.println("normally I do good bowling , but I can't do batting");
}
// you can set wicket keeping strategy too
}

these are our interfaces:
public interface BattingStrategy {
public void doBattingWithStrategy();

public interface BowlingStrategy {
public void doBowlingWithStrategy();

Concreate implemementations of strategies.
         public class GoodBattingStratergy implements BattingStratergy{
                          public GoodBattingStratergy(){
                             // set good parameters
                                 //set good minimum  money too
                              }
             public void doBattingWithStrategy(){
                            // use a good algorithem for batting
                        // then  do batting
                 }
}
similar way you can implement other classes too. Differnt algorithmes like lefthand ,righthand , offspin, spinners .... as long as you implement the strategies.
let us see two simulators ie match:
public class GenuineMatch {
   public static void main(String[] args) {
    CricketPlayer  rajeshkootrapalli = new Batsman();
     CricketPlayer sheldoncooper = new Bowler();
     rajeshkootrapalli.doBatting();
      rajeshkootrapalli.doBowling();
       sheldoncooper.doBatting();
        sheldoncooper.doBowling();
}
}
public class  FixedMatch {
   public static void main(String[] args) {
    CricketPlayer  rajeshkootrapalli = new Batsman();
     CricketPlayer sheldoncooper = new Bowler();
   rajeshkootrapalli.setBattingStrategy(new BadBattingStrategy());
     rajeshkootrapalli.doBatting();
      rajeshkootrapalli.doBowling();
      sheldoncooper.setBowlingStrategy(new BadBowlingStrategy());
       sheldoncooper.doBatting();
        sheldoncooper.doBowling();
}
}

This way if you encapsulate algorithems in different classes and we can fix the match on the spot without anybodies' attention or concern.  This is how online gaming works.  All winning strategies or loosing strategies are encapsulated in different classes. You can purchase them according to the money. Good algorithems always costs lots of money.

hence the Title:

  How to make money from Strategy patterns.      

Monday, 13 January 2014

How to...

In this blog I am going to write about decorator pattern of OO designing.
examples :
InputStream:
concreate classes:FileInputStream,StringBufferInputStream,ByteArrayInputStream.
decorator:FilterInputStream:
Concreate decorators:
PushBackInputStream,BufferedInputStream,DataInputStream,
LineNumberInputStream
Design Principle :Classes should be closed for modifications but open for extensions. 

Decorator : "Attach additional responsibilities to an object dynamically.Decorators provide a flexible alternative to subclassing for extending functionality" - The book Head First Design Patterns.

 For this Pattern I made up my mind that I should think like an Indian Lady.  Let us consider a family bussiness in a street of Bombay,as it started as a small saree shop 20 years ago.  The bussiness got boomed since then ,so that now they are the owner of small enterprice and they have shops from this end  to the other end of that street. One corner  they have saree shops of various types of sarees like silk, nylon,polyester, cotten etc. On the other corner they have shops they sell matching falls, matching blouse, matching skirts,matching slippers, matching necklace and earings, matching bangles and at last matching Bindi(to put on the forehead); Once you buy a saree from them that is it, they will take you  to other shops to get all the matching items and you can then pay the bill at the end. (It is a family bussiness). 
Now we can  consider "WearableProducts" as a abstract class. All  sareePoducts such as "NylonSarees","SilkSarees " .... are thier concreate implementations.  There is an abstrct class "MatchingProducts"  class extands "WearableProducts"  is our decorator which takes a WearableProduct in its constructor.        
Here is our Component class(WearableProducts)
public abstract class WearableProducts{
string itemName = "";
public String getItemName (){
return itemName();
}
public abstrct double getPrice();
public abstract  void createBill();
public abstract Color getColor();
public abstract void setColor(Color color);
//more methods if you want to
}
This is our decorator class:
public abstract class MatchingProducts extends WearableProducts{
   public abstract String getItemName();
   public abstract boolean findMaching();
//more methods if you want to
}
concreate implemetation of WearableProducts:
public class NylonSarees extends WearableProducts{
Color color;
 public NylonSarees (){
     itemName = "nylon saree";
     
}
public double getPrice(){
return 400.00;
}
   public Color getColor(){
       return color;
}
public  void createBill(){
 System.out.println( " "+getItemName()+" "+getPrice());
}
public void setColor(Color color){
this.color = color;
}
}
My contreate decorator:-
public class  BlouseMatchers extends MatchingProducts{
WearableProduct saree;
String itemName;
Color color;
//define an array of colors;
public BlowseMatchers(WearableProducts saree){
this.saree = saree;
}
public boolean findMatching(){
//gothrough the array of colors
if(a[i] == saree.getColor()){
this.setColor((Color)a[i]);
}
return true;
else
return false;
}
public string getItemName(){
return itemName;
}
public double getPrice(){
  return(saree.getPrice()+100.00);
}
public void ceateBill(){
    saree.createBill();
     System.out.print(" "+getItemName()+" "100.00");
     System.out.Println(" "+getPrice());
}
   public Color getColor(){
       return color;
}
public void setColor(Color color){
this.color = color;
}

}
You can create more decorators like this. FallMatchers,BangleMatchers,NecklaceMatchers .....And you can create SilkSarees,CottonSarees are WearableProduct concreate classes.
while testing
WearableProduct saree = new NylonSarees();
MatchinProducts blouse = new BlouseMatchers(saree);
if (blouse.findMatching()) &&(shoppingisOver)

blouse.createBill();
else ...... you are allowed to go to further decorative stores wrap it with decorators.
MatchingProducts bangles = new BangleMatchers(blouse); (do this only if you get the matching blouse)
MatchingProducts slipper = new SlipperMatchers(bangles);
.......
bindi. createBill(); (this method calls others like recursive method, don't you think it is very powerful?)

I hope I did not confuse Indian Women.

Title:

How To explain "Decorator Pattern" for Indian Women.


Thursday, 9 January 2014

How to....

As I have decided to take a break from writing codes, time for some reading.  I am always interested in object oriented designs, I went back and started to study design patterns again. While I am reading I always make sure that I understand it properly so that I can make it easy for remember as I come back again. This time I started to forget what I have read before, so I thought I am going to write it in a blog so that I can quickly go through if I wanted to. In this blog I will write about Adapter pattern in OO design Patterns.
Adapter Pattern: “Converts the interface of a class into another interface clients expect. Lets classes work together that couldn’t otherwise because of incompatible interface.”
Let us try in a way that we should remember this patterns when we hear the name.
Say, I bought a computer from US but it only works with the American Socket. Here the plug and a computer is our client only understands AmericanSocket Interface. But I have a EuropeanSocket Interface. I build a EuropeanAdapter which takes a EuropeanSocket object.

       public interface AmericanSocket {

               public void optTwoPins();

               public void setPower();

    }

        public class kitchenSocket implements AmericanSocket {

         public void optTwoPins(){

            System.out.println(“I can opt for two pins”);

    }

          public void setPower(){

            System.out.println(“I can work with 120Volts ”);

     }

    }

Now here is EuropeanSocket

   public interface EuropeanSocket {

               public void optThreePins();

               public void setPower();

    }

        public class studySocket implements EuropeanSocket {

         public void setThreePins(){

            System.out.println(“I can opt for three pins ”);

    }

          public void setPower(){

            System.out.println(“I can work with 240Volts ”);

     }

    }

Here is the adapter:

public class EuropeanAdapter implements AmericanSocket{

    EuropeanSocket socket;

    public EuropeanAdapter(EuropeanSocket socket){

     this.socket = socket;

}

public void optTwoPins(){

socket.optThreePins();

}

public void setPower(){

// use a transformer to step down the power.

socket.setPower();

}

}

Now test it

public class AmericanComputer {

    public static void main(String[] args){

        EuropeanSocket socket = new StudySocket();

         AmericanSocket americansocket = new EuropeanAdapter(socket);

          americansocket.optTwoPins();

         americansocket.setPower();

}

}

My computer works now. My computer plug sees adapter as a American Socket.
Title always at the End.

How to remember Adapter Pattern