Open Closed Client/Server Example

Hesper
Erstie
Erstie
Beiträge: 18
Registriert: 26. Mai 2012 13:14

Open Closed Client/Server Example

Beitrag von Hesper »

As mentioned in the paper http://www.objectmentor.com/resources/articles/ocp.pdf, an example of Client/Server, how client is unchanged if we change the server? It would be very helpful if someone can provide a short example. I can understand it theoratically, but when i think of it in coding, it does not make sense to my dumb mind :(

radio_controlled
BASIC-Programmierer
BASIC-Programmierer
Beiträge: 107
Registriert: 8. Okt 2010 20:31

Re: Open Closed Client/Server Example

Beitrag von radio_controlled »

Hi
You can achieve it, for example, by using the dependency injection pattern:

Code: Alles auswählen


interface IServer {
  public void someMethod();
}

class ServerA implements IServer{
  public void someMethod(){ print("Hello ");
}

class ServerB implements IServer{
  public void someMethod() { print ("World!");
}

class Client {
  private IServer server;

  public Client(IServer server){
    setServer(server);
  }

  public void setServer(IServer server) {
    this.server = server;
  }

  public void someMethod(){
    server.someMethod();
  }
}

class UsageExample {
  public static void usage(){
    Client client = new Client(new ServerA());
    client.someMethod(); // prints Hello

    client.setServer(new ServerB());
    client.someMethod() // prints World!
  }
}
In this example, you can exchange ServerA and ServerB even after creating the client. You can even add more classes which implement the IServer interface and you don't have to touch the Client nor the IServer, ServerA, ServerB code. You can take it further and use some framework for Dependency Injection and configure the class which you want to use, that way you even avoid recompiling the code. The above example conforms the OCP for Client.

A counterexample would be

Code: Alles auswählen

class A { ...}
class B { ... }
class C {
  public void someMethod(Object o) {
    if(o instanceof A) { A.xxx() }
    else if (o instanceof B) { B.xxx() }
  }
}
You would need to change class C every time you create a new class which should do something in someMethod.

Or so I think. Did not read the paper yet :P

Hesper
Erstie
Erstie
Beiträge: 18
Registriert: 26. Mai 2012 13:14

Re: Open Closed Client/Server Example

Beitrag von Hesper »

Thank you so much. It helped me a lot.

Antworten

Zurück zu „Archiv“