akLearn's avatar

OCP Principle and factory pattern

I saw an example of factory method pattern and it had this code in the client.

if (config.OS == "Windows") then
    dialog = new WindowsDialog()
 else if (config.OS == "Web") then
     dialog = new WebDialog()

This violates the OCP principle. If tomorrow you add more types/classes then you'll have to modify the code. I've been searching the net but haven't found a solution.

0 likes
9 replies
Tray2's avatar

Why not make the Windows class and the WbClass both have a Dialog method, and instead of newing up the classes here you pass the object into the method?

akLearn's avatar

@Tray2 Can you write up some psuedo code? Not getting you

I know the factory pattern but I don't know how to do that without breaking the OCP.

akLearn's avatar

@Tray2 I read the article. The problem i'm facing is having the customer decide at runtime what they want.

So, if there's an interface which Facebook and lInkedIn use. The customer decides at runtime where to share a specific post how do I do this without using if conditions. The only reason to avoid If/else is to keep OCP going.

Is this making sense or am I confused about the topic?

martinbean's avatar

@aklearn Think you’re worrying too much.

At some point you’re going to need a conditional depending on what option the user has selected, no matter what design pattern you employ or principles you try to follow.

webrobert's avatar
Level 51

in php you could also use the the config string to new up the class.

$config = "Windows"; 
$class  = "\App\Dialogs\{$config}Dialog"; // namespace like Laravel [note the forum is removing the double backslash after Dialogs]
$dialog = new $class();
// do some catch for when you forgot to add a particular dialog to dialogs folder
  // WindowsDialog
  // WebDialog
akLearn's avatar

@webrobert So on the front-end of the site you have them pick from a drop down or what not. Then on the back-end ...

// pseudo code beloe // check if this class exists in a specific folder where all the options(classes) are // run the code you suggested

Please or to participate in this conversation.