Pages

Friday, August 24, 2012

proxy design pattern using java

what is proxy design pattern?
It is a design pattern that uses a proxy to control access to another object. What is the meaning of proxy? It means acting something on behalf of something. In this case, the client access an object through proxy.
So to what kind of objects do we need to provide a proxy?
Usually for objects that takes a lot of memory, files, resources that are expensive or hard to duplicate.

Below a simple implementation of the proxy design pattern.

Interface Game{
   void playGame();
}

public RealGame implements Game{

    private String game;

    public RealGame(String game){
         this.game = game;
         loadGame(game);
    }

    private loadGame(String game){
           System.out.println("loading game : "+game);
    }

    public void playGame(){
         System.out.println("playing game: "+ game);
    }
}

public ProxyGame implements Game{

     private RealGame game;
     private String gameName;
     public ProxyGame(String game){
         this.game = game;
   }
 
   public void playGame(){
      if(game==null)
           game=new RealGame(gameName);
      }
      game.playGame();
}



public DemoProxy{

   public static void main(String[] args){
       Game proxyGame = new ProxyGame("modern warfare");
        proxyGame.playGame();
   }
}

No comments:

Post a Comment