Patterns (contd) Software Development Process Design patterns used to handle change More time extending and changing code than developing it. The Strategy design pattern handle change by selecting from a family of external algorithms rather than rewrite. Design point: Make code closed for modification of code, but open for extension Problem Computer object created Description Method returns Getting a Computer Problem Program has to change every time Customer changes options Decorator Pattern Wrapper code used to extend your core code Extend a class dynamically at runtime Decorator uses wrapper code to extend core functionality - decorating the code Decorator Pattern description() returns “You are getting a computer” Wrapper description() returns “You are getting a computer and a disk” Wrapper description() returns “You are getting a computer and a disk and a monitor” Decorator Pattern Core component: Computer Variables holding computer objects should also be able to hold objects that wrap computer objects. Extend the wrapper classes from the Computer class. Abstract class cannot be instantiated Ensures all wrappers are consistent Developers have to provide their own description Decorator Pattern Method calls the core computer object’s description method and adds “and a disk” Decorator Pattern Method calls the core computer object’s description method and adds “and a disk” Extend the core object by wrapping it in decorator wrappers. Avoids modification of the core code. Each successive wrapper called the description method of the object it wrapped and added something to it. Factory Pattern Based on type, call the Connection method Factory Pattern Create a method that returns the correct connection type Factory Pattern New operator used to create OracleConnection objects. New operator used to create SqlServerConnection objects, and MySqlConnection objects. New operator to instantiate many different concrete classes Code becomes larger and needs to be replicated in many places Factor that code out into a method. Code keeps changing Encapsulate code into a factory object Goal: Separate out the changeable code and leave the core code closed for modification Building the Factory Creating the Factory FirstFactory class encapsulates the connection object creation Pass to it the type of connection (“Oracle”, “SQL Server”,) Use the factory object to create connection objects with a factory method named createConnection Building the Factory Create the FirstFactory class. Save the type of the database, passed to the FirstFactory class’s constructor. Object-creation code changes Check which type of object to be created (OracleConnection, SqlServerConnection, and then create it. Factory Class Create the Abstract Connection Class Core code should not be modified or has to be modified as little as possible. Using the connection object returned by the new factory object Use t.