vendredi 24 novembre 2017

Factory Method pattern vs ordinary abstract class implementation

I'm trying to understand the Factory Method pattern. I've managed to distinguish it from the Simple Factory, but now I don't get why it's actually called a "pattern". Please, look at my example below:

Class Diagram link

Sample java code for Messenger:

public String exchangeMessages(String messageToSend) {
   Socket socket = getSocket();
   socket.open();
   socket.send(messageToSend);
   String receivedMessage = socket.receive();
   socket.close();
   return receivedMessage;
}

And for Client:

public static void main(String[] args) {
   Messenger messenger = new TCPMessenger("127.0.0.1", 4321);
   String result = messenger.exchangeMessages("Hello!");
   System.out.println(result);
}

If I understand correctly, everything makes sense because exchangeMessages method exists. We use the abstract factory method getSocket inside it and thanks to it we:

let subclasses decide which class to instantiate

But isn't it just an ordinary abstract class implementation? We take advantage of the code shared by both TCPMessenger and UDPMessenger - for me, this is not a pattern but a core feature of Object-Oriented Programming that everybody knows from the beggining of OOP language learning!

Moreover, I think that naming this creational is very confusing. We actually care about exchangeMessages method, so Client (part of the code that uses our "pattern") is not even aware of the Socket class which creation we're all about. It's more like a way to implement Messenger functionallity (which can be easily extended etc...) than a way to really create something.

Am I missing the point or is my example invalid? Please guys, let me know what do you thing about it.

Thanks in advance!

Aucun commentaire:

Enregistrer un commentaire