Senin, 17 Maret 2014

Great Example of Open Closed Design Principle in Java




Great Example of Open Closed Design Principle


I am big fan of design pattern article and love to read articles on design patterns and recently wrote about decorator design pattern in JavaObserver patternstatic factory pattern and about Singleton pattern. Today I come across this good article on open closed design pattern, what I like most is there example and clear way of explanation, first example is true value and it will help you understand open closed principle very quickly and second example is also not bad. I have also shared many questions on design patterns and Object oriented design principles like 10 Java singleton interview questions , which discusses some of the most common questions on Singleton pattern like how to write Thread-Safe Singleton class , should we use Enum as Singleton or not etc and 20 design pattern interview questions, if you are preparing for senior level Java interview, where questions from design is expected, its worth looking for quick review.





open closed design principle exampleOne word about Open Closed principle is a design principle which says that a class should be open for extension but closed for modification. Open Closed Principles is one of the principle from SOLID design principle where it represent "O". Read more about OOPS and SOLID design pattern in my post 10 OOPS and SOLID design principles Java programmer should know.  





In Simple language Open closed design principles says that new functionality should be added by introducing new classes, methods or fields instead of modifying already tried and tested code. One of the way to achieve this is Inheritance where class is extended to introduce new functionality on top of inherited basic features.





Benefit or Open Closed Design Principle:


1) Application will be more robust because we are not changing already tested class.


2) Flexible because we can easily accommodate new requirements.


3) Easy to test and less error prone.






How to make code extensible


Basic principle of making your code extensible and following open closed principle is providing object to class at run time and making use of polymorphism to invoke extended functionality.


If functionality is hard Coded than it wouldn’t be extensible but if you write interface and provide implementation of that interface at run time you make it extensible.








For detailed example see this link open closed design pattern on sanaulla blog post http://blog.sanaulla.info/2011/11/19/solid-open-closed-principle/







Interview Questions you may like

































Source:http://javarevisited.blogspot.com/2011/11/great-example-of-open-closed-design.html

Tidak ada komentar:

Posting Komentar