This is the second article about design patterns. In the first article I have discussed about creational design patters and now I will describe another set of patterns called Structural design patterns.

In software engineering, structural design patterns are design patterns that ease the design by identifying a simple way to realize relationships between entities.

The adapter pattern is a design pattern that is used to allow two incompatible types to communicate. Where one class relies upon a specific interface that is not implemented by another class, the adapter acts as a translator between the two types.

Adapter pattern is structural pattern which defines a manner for creating relationships between objects. This pattern translates one interface for a class into another compatible interface. Adapter pattern is newer used when creating a new system. It is usually implemented when requirements are changed and we must implement some functionality of classes which interfaces are not compatible with ours.

The UML diagram below describes an implementation of the adapter design pattern.
Diagram consists of four parts:

Client: represents the class which need to use an incompatible interface. This incompatible interface is implemented by Adaptee.

ITarget: defines a domain-specific interface that client uses. In this case it is an simple interface, but in some situations it could be an abstract class which adapter inherits. In this case methods of this abstract class must be overriden by concrete adapter.

Adaptee: represents a class provides a functionality that is required by client.

Adapter: is concrete implementation of adapter. This class translates incompatible interface of Adaptee into interface of Client.

In this example I have decided to create a simple serialization application which allows you to serialize objects into JSON or XML format. For example I have created PersonInfo class which will be serialized. For serialization I have used JavaScriptSerializer and XmlSerializer classes. This classes play in this example role as Adaptees with incompatible interfaces. ISerializerAdapter (ITarget) is interface which must by implemented by concrete adapter. It has one method called Serialize which serializes object into appropriate format. JSONSerializerAdapter and XMLSerializerAdapter classes implement ISerializerAdapter interface. This two classes are adapters.

he bridge pattern is a design pattern that separates the abstract elements of a class from its technical implementation. This provides a cleaner implementation of real-world objects and allows the implementation details to be changed easily.

Bridge pattern is very valuable pattern because it allows you to separate abstract elements of class from the implementation details. This pattern can be used, when the class vary often because changes to the code base can by made vary easily with minimal knowledge about the program.

Sometimes an implementation can have two or more different implementations. Let’s consider a program that handles persistence of objects on different platforms. Some of objects should be saved into database and other objects into file system. When simply extends the program with this functionality, it could cause problems because we binds abstraction with implementation. In this case it is more suitable to use Bridge pattern and separate abstraction from its implementation. If we don’t use this pattern, we will find that implementation details are included within an abstraction.

On of the biggest benefits of Bridge pattern is ability to change implementation details at run time. This could permit the user to switch implementations to determine how the software interoperates with other systems.

The UML diagram below describes an implementation of the bridge design pattern.
Diagram consists of four parts:

Abstraction: defines an abstraction interface. It acts as base class for other refined abstraction classes. It also holds reference to particular implementation that it is using for platform specific functionality.

RefinedAbstraction: it provides more specific variations upon abstraction but it doesn’t contain any implementation details. De facto it only extends abstraction.

Implementor: it defines the interface for implementation classes.

ConcreteImplementor: this class inherits from RefinedAbstraction class. There may be more than one instances of Implementor classes providing the same interface but platform specific functionality.

In this example I decided to create a simple messaging application. For this purpose Message class was created. This class acts as Abstraction for UserEditedMessage class. This class has one protected filed of type MessageSenderBase. MessageSender base is implementor and abstract class from all concrete implementations of message senders. Three message senders were created: EmailSender, MsmqSender and WebServiceSender. This is only demonstrative example and hence no realistic functionality of this senders is implemented.

The composite pattern is a design pattern that is used when creating hierarchical object models. The pattern defines a manner in which to design recursive tree structures of objects, where individual objects and groups can be accessed in the same manner.

When the program needs to manipulate a tree structure of objects, you can use composite design pattern. The intent of this design pattern is to compose objects into tree structures to represent part-whole hierarchies. Composite lets clients treat individual objects and compositions of objects uniformly.

The UML diagram below describes an implementation of the composite design pattern.
This diagram consists of three parts:

Component: is an abstraction for all components, including composite ones. It declares the interface for objects in the composition. Sometimes it defines an interface for accessing a component's parent in the recursive structure, and implements it if that's appropriate.

Composite: this is a key element of this design pattern. It represent a Composite components. Composite element are elements which have child elements. It implements the methods to add and remove children elements and it implements all Component methods, generally by delegating them to its children.

Leaf: represents leaf objects in the composition and implements all Component methods.

The good examples how to demonstrate this design pattern in real world are graphic editors. Every shape that can be created by graphic editor can be a basic or complex. The example of a simple shape is a line. Complex shape consists of many simple shapes. This shapes (complex and simple) have a lot of operations in common. One of the operations is rendering of a shape to the screen. Since shapes follow a part-whole hierarchy, composite pattern can be used to enable the program to deal with all shapes uniformly.
In this example I have created IShape interface that acts as Component. All composites and leafs must implement this interface. This interface consists of public property Name and method Render(). Another class called ComplexShape is Composite class. It has one private collection of child shapes _shapes. This collection is managed by AddShape() and RemoveShape() methods. This collection may contains every object which implements IShape interface. Render method of ComplexShape class loops through collection of child elements _shapes and call their Render() method. The last three classes: Rectangle, Circle and Line represents Leafs classes.

The decorator pattern is a design pattern that extends the functionality of individual objects by wrapping them with one or more decorator classes. These decorators can modify existing members and add new methods and properties at run-time.

Extending object’s functionality can be done statically (at compile time) by using inheritance or or dynamically (at run time) by wrapping them in an object of a decorator class. Decorator pattern is applied on individual objects, not classes. Decorator pattern is an alternative to subclassing. This pattern allows you to create a multiple decorators that can be stacked on the top of each other, each time adding a new functionality to the overriden method.

The UML diagram below describes an implementation of the decorator design pattern.
This diagram consists of four parts:

ComponentBase: is a base abstract class for all concrete components and decorators. This class defines standard members, that must by implemented by this types of classes.

ConcreteComponent: this class inherits from ComponentBase. There may be multiple concrete component classes, each defining a type of object that may be wrapped by the decorators.

DecoratorBase: prepresents abstract base class for all decorators. It adds a constructor that accepts a ComponentBase object as its parameter. The passed object is the component that will be wrapped. As the wrapped object must inherit from ComponentBase, it may be a concrete component or another decorator. This allows for multiple decorators to be applied to a single object.

ConcreteDecorator: this class represents the concrete decorator for a component. It may include some additional methods which extends functionality of components. Operations members can be used in two manners. They can by unchanged and in this case the base method of component is called or the operation may be changed and in this case the operation method is changed or entirely replaced by new implementation.

Let’s take a loot at real world example. In this example you can prepare your custom favourite sandwich. In this case we have Sandwich class which is an component base class. This class has two public abstract methods. GetDescription method returns full name of sandwich with all ingredients. Second method called GetPrice returns price of current sandwich. I have created two sandwiches: TunaSandwich and VeggieSandwich. Both of this classes inherit from Sandwich class. SandwichDecorator class is a base class for all decorators. This class inherits from Sandwich class too. Three decorators were prepared: Olives, Cheese, Corn. This decorators override GetDescription and GetPrice methods of the Sandwich class. The first step is to create a concrete sandwich. You can choose from two options: VeggieSandwich and TunaSandwich. If it is done, you can add some ingredients by creating of appropriate decorator and wrapping your sandwich by this decorator. If you want to add another ingredient, just create a new instance of decorator and wrap sandwich by this new decorator. By calling of method GetDescription you will get name of sandwich with all ingredients.

The facade pattern is a design pattern that is used to simplify access to functionality in complex or poorly designed subsystems. The facade class provides a simple, single-class interface that hides the implementation details of the underlying code.

Facade pattern is generally used to simplify interface to a larger body of code. This pattern is very helpful when you deals with many independent classes or classes that require the use of multiple methods, especially when they are difficult to use or difficult to understand. We can tell that facade pattern is some kind of wrapper that contains a set of members they are easy to understand and use. This pattern us used when wrapped subsystem is poorly designed and you can have no possibility to refactor it’s code.

Facade pattern makes software library easier to use, understand and test. It makes library more readable and can reduces dependencies.

The UML diagram below describes an implementation of the facade design pattern.
This diagram consists of three parts:

Facade: This class contains the set of simple functions that are made available to its users and that hide the complexities of the difficult-to-use subsystems.

PackageA/B: The complex functionality that is accessed via the facade class does not necessary reside in a single assembly. The packages in the diagram illustrate this, as each can be an assembly containing classes.

ClassA/B: These classes contain the functionality that is being presented via the facade.

In this example we need to start computer. Computer class acts as facade which encapsulates other complex classes represented by: HardDrive class, Memory class and CPU class. Each of this classes has operations which must be performed when Start() method of Computer class is called.

The flyweight pattern is a design pattern that is used to minimize resource usage when working with very large numbers of objects. When creating many thousands of identical objects, stateless flyweights can lower the memory used to a manageable level.

Sometimes programs work with a large number of objects which have the same structure and some states of this objects don’t vary in time. When we use traditional approach and we create instances of this objects and fill state variables with values, the memory and storage requirements may unacceptably increase. To solve this problem we can use Flyweight pattern.

A flyweight is an object that minimizes memory use by sharing as much data as possible with other similar objects; it is a way to use objects in large numbers when a simple repeated representation would use an unacceptable amount of memory. For each of objects which use shared data only reference to shared object is saved.

The flyweight design pattern often uses a variation on the factory method pattern for the generation of the shared objects. The factory receives a request for a flyweight instance. If a matching object is already in use, that particular object is returned. If not, a new flyweight is generated.

The UML diagram below describes an implementation of the flyweight design pattern.
This diagram consists of four parts:

FlyweightBase: declares an interface through which flyweights can receive and act on extrinsic state.

ConcreteFlyweight: implements the Flyweight interface and adds storage for intrinsic state (shared state), if any. A ConcreteFlyweight object must be sharable. Any state it stores must be intrinsic, that is, it must be independent of the ConcreteFlyweight object's context.

UnsharedFlyweight: not all Flyweight subclasses need to be shared. The Flyweight interface enables sharing, but it doesn't enforce it. It is common for UnsharedFlyweight objects to have ConcreteFlyweight objects as children at some level in the flyweight object structure.

FlyweightFactory: The factory creates and manages flyweight objects. In addition the factory ensures sharing of the flyweight objects. The factory maintains a pool of different flyweight objects and returns an object from the pool if it is already created, adds one to the pool and returns it in case it is new.

In a war game example UnitFactory can create military units. In this example I have created two types of units: Soldier and Tank. This classes are concrete flyweights which inherits from Unit flyweight base class.

UnitFactory class contains method called GetUnit which accept one parameter that specify type of unit to create. This class has one private dictionary of unit types. When new unit is required, the first step is to look into this dictionary whether this type of unit was created earlier. If yes, program returns reference to this unit. If no, it just create a new unit and places it into dictionary.
You can control the number of instances of each unit type by static field NumberOfInstances.

Proxy in a most general form is an interface to something else (Subject class). Proxy can be used when we don’t want to access to the resource or subject directly because of some base of permissions or if we don’t want to expose all of the methods of subject class. In some cases proxies can add some extra functionality. Using proxies is very helpful when we need to access resources which are hard to instantiate, are slow to execute or are resource sensitive.

The UML diagram below describes an implementation of the proxy design pattern.
This diagram consists of three parts:

SubjectBase: Interface (or abstract class) implemented by the RealSubject and representing its services. The interface must be implemented by the proxy as well so that the proxy can be used in any location where the RealSubject can be used.

RealSubject: represents a complex class or resource sensitive class that we wish to use in more effective manner.

Proxy: this si the key stone of this pattern. It references to RealSubject object. Application executes methods of proxy class which are transferred to RealSubject’s methods.

In this example I have created Order application which displays information of selected order. We have the OrderRepositoryBase class which is an abstract class for ProxyOrderRepository and RealOrderRepository classes. RealOrderRepository class is a RealSubject which we want to consume by our application using ProxyOrderRepository.

Also we have a set of entities which represents data of RealOrderRepository class. In this example Order can have a multiple OrderDetails but one Customer. This properties could be filled by methods of RealObjectReporsitor (GetOrderDetails and GetOrderCustomer). That means if we want to get all of the information about the order, we must call three different methods of RealOrderRepository class (GetOrder, GetOrderDetails and GetOrderCustomer). ProxyOrderRepository has all of this methods too. In case of GetOrderDetails and GetOrderCustomer it calls directly methods of RealObjectRepository class. In case of GetOrder the situation is a little bit different. It doesn’t only call method of RealObjectRepository but it sets OrderDetails and Customer properties of Order returned by GetOrder method of RealObjectRepository. When all if the properties of Order object are populated, Order is returned to the caller application.