According to GoF design pattern authors "software entities (classes, modules, functions, etc.) should be open for extension, but closed for modification".
Example
In the below code we are handling ADD and SELECT operations and there is a chance to come additional operations like update or delete. So this curOperation method is not closed for modification.
Example
In the below code we are handling ADD and SELECT operations and there is a chance to come additional operations like update or delete. So this curOperation method is not closed for modification.
package com.vinod;The same task we can define another way
public class CrudOperation {
public String crudOperation(String details, String operation) {
String result = null;
if (operation.equals("ADD")) {
// call add logic
result = details + "Inserted";
}
if (operation.equals("SELECT")) {
// call select logic
result = details + "details";
}
return result;
}
}
package com.vinod;
/**
*@authorvinod.kumaran
*
*/
public interface Operation {
abstract String executeOperation(String data);
}
package com.vinod;
public class SelectOperation implements Operation {
@Override
public String executeOperation(String data) {
return "Selected data is" + data;
}
}
package com.vinod;
public class AddOperation implements Operation {
@Override
public String executeOperation(String data) {
return "Record inserted";
}
}
package com.vinod;
public class UpdateOperation implements Operation {
@Override
public String executeOperation(String data) {
// TODO Auto-generated method stub
return data+"Updated";
}
}
So the above three classes are closed and the interface we can use it for further implementations
package com.vinod;
/**
*@authorvinod.kumaran
*
*/
public class OperationTest {
public static void main(String[] args) {
Operation select = new SelectOperation();
Operation add = new AddOperation();
Operation update = new UpdateOperation();
System.out.println(select.executeOperation("helloworld"));
System.out.println(add.executeOperation("helloworld"));
System.out.println(update.executeOperation("helloworld"));
}
}
No comments:
Post a Comment