java - Up to what extent can you prevent modifying existing code when using design patterns? -


i taking design patterns class in school, , have read through chapters of head first design patterns. i'd find out extent can design patterns prevent rewriting of existing code.

let take duck classes , flybehavior classes example. have in public static void main(string[] args) following code:

duck mallard = new mallardduck(new flywithwings()); 

am right in saying inevitable you'll have modify main() method when want add new strategy? in way, are modifying existing code, right? referring part concrete strategy class mentioned: new flywithwings().

if implemented factory method pattern in code, prevent having concrete class (flywithwings) being mentioned @ all:

public flybehavior returnbehavior(flybehaviorfactory factory, string behaviortype) {     return factory.getflybehavior(behaviortype); } 

and thus, have following line of code:

duck mallard = new mallardduck(returnbehavior(flyfactory, "wings")); 

this way, portion of program not have know flybehaviorfactory use. yet, main() method still have specify parameters in returnbehavior method in order know factory create strategy. thus, right in saying you'll still have modify main() if added new flybehavior class, , wanted add parameter returnbehavior()?

can 1 improve situation further?

in current example, hard-coding parameters passed factory , deciding behavior @ compile time.

duck mallard = new mallardduck(returnbehavior(flyfactory, "wings")); 

this can changed plugin particular behavior @ runtime instead of compile time :

duck mallard = new mallardduck(returnbehavior(flyfactory, args[0])); 

with above change, never have change main method. factory can written in way throws exception when behavior recieved @ runtime not available :

if(behaviortype.equals("wings") {    //...create flywithwings } else{   //throw appropriate exception indicating behavior not exist } 

that being said, inevitable change code if new behavior introduced. although, change in 1 single place , far behind in application possible, i.e factory whole point of factory in first place. also, when create new flybehavior, doing extending existing class. inline open-closed principle


Comments

Popular posts from this blog

asp.net mvc - SSO between MVCForum and Umbraco7 -

Python Tkinter keyboard using bind -

ubuntu - Selenium Node Not Connecting to Hub, Not Opening Port -