As software development has grown over the years, patterns in the way developers write code began to emerge. often there was a better way to approach using specific problems, and these approaches caught on. generation of them have been formalized into design patterns that can be used to address very specific coding challenges. this new column will present a variety of useful patterns applicable to a wide range of projects that will help you find easy solutions to your development problems. |
Esign patterns are a powerful tool for designing flexible soft-ware. they provide well-tested solutions to recurring software design problems. one such widely used pattern is the concrete factory. the factory pattern decouples objects from knowledge about the creation of other objects or even the underlying type of those objects. too often, however, the factory pattern is not applied optimally, creating subtle coupling and low cohesion issues between varous participant ipants of the pattern. in this column, I'll use reflection in. net to create factory classes for C #, removing dependencies common in some implementations of this pattern. Two of the sacred tenets of sound software design are keeping elements loosely coupled, yet highly cohesive. coupling determines how strongly or closely related software components are, while cohesion relates to how well focused a software unit is, whether it's a method, class, or class library. The concrete factory design pattern The concrete factory is one of the most widely used patterns. in order for an object A to send a message to object B, a must have a reference to B, which means that Class B must be instantiated and a reference to object B must be available to. if a instantiates B directly, A has a direct reference to B, but now they are tightly coupled, since a must know how to create B. in order to reduce tight coupling between these two objects, it is best to give the responsibility of creating B to a factory class, C, so that in addition to fetch the strength of coupling between A and B, other potential consumers of B can request an instance of B from C as well. this is what the concrete factory Design Pattern provides. Note that coupling is not eliminated between objects A and B; rather, it is weakened because a no longer needs to know how to create B. A further weakening of this coupling wocould be achieved if factory class C returned an interface to object B (let's call it I), rather than the concrete object itself. this wowould ensure that no matter how many implementations of I exist, object a wowould only know of I. the reason an interface renders coupling even weaker is that object A is further specified acted from new implementations of I. In the factory pattern there is a client, a factory, and a product. the client is any object that needs an object from the factory. the product is the object returned to the client by the factory. Common implementations There are quite a few variations of the factory pattern. I'll look at the pros and cons of two of the most common approaches, then I'll introduce a new approach that uses reflection. The first implementation I'll examine uses Abstract and concrete factories. this implementation shocould not be confused with the abstract factory pattern, which handles the creation and return of families of objects. suppose you have a computer parts store inventory application in which inventorymgr is the client class, partsfactory, monitorinvfactory, and keyboardinvfactory make up the factory, and ipartsinventory is the product returned by the factory. the uniied Modeling Language (UML) divisor in Figure 1 has strates this implementation. here, mainclass is a class that sends a request to inventorymgr. Figure 1 abstract and concrete factories
In Figure 1, mainclass simply represents an object that passes on the user's request to inventorymgr. if mainclass needed to replenish the inventory of monitors, for example, it wocould send a message to the inventorymgr (see figure 2 ). Take a look at the code in the abstract factory partsfactory and the concrete factories monitorinvfactory and keyboardinvfactory in figure 3. although this is a reasonable approach to implementing the factory pattern, it has some sort comings. consider how coupling manifests itself and to what degree it is present in this pattern. the inventorymgr class looks good (coupling is low) since it's shiel DED from knowing about any of the concrete factories. the addition of new concrete factories in the future will not affect it. inventorymgr is also decoupled from the different implementations of ipartsinventory by having a reference to the interface instead of a concrete object. so, what is the problem? One of the axioms in object-oriented design is "don't talk to strangers," meaning that objects shoshould not have a reference to objects they do not absolutely need in order to function properly. if you look at the code fragment for mainclass in Figure 2, this rule is violated because mainclass creates concrete factories. mainclass does not truly need to know about concrete factories since it does not send a message to them. it simply creates them and passes them on to inventorymgr. this results in an unnecessary coupling between mainclass, monitorinvfactory, and keyboardinvfactory. As a general rule, objects shoshould only create other objects if they plan to send a message or messages to those objects, unless their main responsibility is the creation and return of those objects. factories, for instance, are such classes. an adverse effect of unnecessary coupling is lower cohesion. mainclass has lowered its cohesion as well since, given its role as a message forwarding agent, it shocould not concern itself with what concrete factories are needed to process the request. its focus shoshould simply be taking a request, possibly repackaging it, and sending it to inventorymgr for further processing. as you'll see later on, reflection helps remove unnecessary coupling and improve cohesion in all classes that participant in the factory pattern. Let's examine another popular Implementation of the factory pattern. this approach does not make use of abstract factories. it only uses a concrete factory to create objects; therefore it is considerably less complex. let's take a look at what the code looks like in mainclass, inventorymgr, and partsfactory. ipartsinventory has not changed (see figure 2 ). monitorinvfactory and keyboardinvfactory (see figure 3) are no longer needed, since a single concrete factory class in now being used. the most striking change is the addition of an enumerator, enminvparts. Figure 4 shows that the code in mainclass is significantly cleaner, less coupled, and more cohesive than the previous implementation in Figure 2. mainclass is no longer "talking to strangers. "instead of being coupled to factories, it is now coupled to the enumeration enminvparts, which simply provides a repackaging mechanism of the command-line request. repackaging the request comes naturally to mainclass since it fits well with its responsibility of simply passing on the request to inventorymgr. although inventorymgr is coupled to partsfactory, coupling has not truly changed, since inventorymgr was previusly coupled to the abstract version of partsfactory by means of parameter passing (see figure 2 ). at first glance, it looks like the coupling and cohesion issues have disappeared, so I can pop the champagne cork and declare victory. well, not yet. If you take a closer look, you see that the coupling has moved from mainclass to partsfactory. although partsfactory is now coupled to ipartsinventory and its implementor objects, coupling does not affect it nearly as adversely as mainclass was affected in the implementation of the factory pattern in Figure 2 because class cohesion has not deteriorated. in other words, partsfactory remains focused. if you cocould remove this hardcoded coupling from the factory, you wocould achieve the lowest possible coupling and highest cohesion in all the classes that make up the implementation of the factory pattern. stay tuned; next I'll describe how reflection can get you pretty close to that lofty goal. A dynamic factory Using Reflection Reflection is simply a mechanic that allows components or classes to interrogate each other at run time and discover information that goes beyond the information gleaned from the publicly available interfaces the objects expose. in essence, reflection enables objects to provide information about themselves (metadata ). The. net Framework provides objects the ability to describe themselves through the use of attributes. an attribute is declared as a class that inherits from system. attribute. once an attribute is defined, it can be attached to types such as interfaces, classes, or an assembly. the code in Figure 5 defines two attributes. The first attribute is inventorypartattribute, which will be attached to the classes that implement the ipartsinventory interface in order to specify which type of parts they handle. The following code between strates how this is achieved: [InventoryPartAttribute(enmInvParts.Monitors)]class MonitorInventory : IPartsInventory { public void Restock() { Console.WriteLine("monitor inventory restocked"); }} [InventoryPartAttribute(enmInvParts.Keyboards)]class KeyboardInventory : IPartsInventory { public void Restock() { Console.WriteLine("keyboard inventory restocked"); }} The second attribute defined in Figure 5 is attached to the ipartsinventory interface. This allows for the interface to be interrogated about which types implement it, like so: [ImplAttr(new Type[]{typeof(MonitorInventory),typeof(KeyboardInventory)})]interface IPartsInventory() { public void Restock();} So far, I have created two attributes and attached them to both the ipartsinventory interface and the classes that implement it (monitorinventory and keyboardinventory ). The class with the largest amount of code changes is partsfactory. this shoshould certainly be no surprise, since it is the class whose hardcoded switch statement I'm trying to replace with code that's more dynamic through the use of attributes. let's examine each line of code of the newly modified partsfactory class in figure 6. The first line retrieves the implattr attribute of the ipartsinventory as shown here: Attr = Attribute.GetCustomAttribute(typeof(IPartsInventory), typeof(ImplAttr)); Next, I cast the ATTR attribute to my custom implattr attribute and the array of types that implement ipartsinventory is retrieved by reading the attribute's implementorlist property: IntrfaceImpl = ((ImplAttr)Attr).ImplementorList; I determine the number of classes that implement the interface by obtaining the length of the intrfaceimpl array: ImplementorCount = IntrfaceImpl.GetLength(0); Next, I loop through the intrfaceimpl array. The first thing I do within the loop is retrieve the inventorypartattribute attribute of each interface implementor class: Attr = Attribute.GetCustomAttribute(IntrfaceImpl[i], typeof(InventoryPartAttribute)); Then, I cast the ATTR attribute to my custom inventorypartattribute and extract its value into the enminventorypart variable: InvPartAttr = (InventoryPartAttribute)Attr;enmInventoryPart = InvPartAttr.InventoryPartSupported; If the value of the extracted enumerator matches the client's enumerator, the class supports the right type of inventory part, so I instantiate it and break out of the loop: if((int) enmInventoryPart == (int)vInvPart) { Obj = Activator.CreateInstance(IntrfaceImpl[i]) InvPart = (IPartsInventory)Obj; break; } Finally, the factory returns the ipartsinventory object: return InvPart; Let's look at what happens when the need arises to add another object that derives from the ipartsinventory interface. i'll name this object mousepadinventory. after updating the enminvparts enumerator to accommodate the new inventory part, I define the new class and attach the inventorypartattribute attribute to it: public enum enmInvParts : int {Monitors = 1, Keyboards, MousePads};[InventoryPartAttribute(enmInvParts.MousePads)]class MousePadInventory : IPartsInventory { public void Restock() { Console.WriteLine("The mouse pad inventory has been restocked"); }} Next, the implattr attribute of the ipartsinventory interface needs to reflect that a new class is implementing the interface: [ImplAttr(new Type[]{typeof(MonitorInventory),typeof(KeyboardInventory), typeof(MousePadInventory)})]interface IPartsInventory() { public void Restock();} Then, I update mainclass to handle the request to replenish the newly added mouse pad inventory. the only change is to add another case for "mousepads" to the mainclass class shown in Figure 4. add the following code right after the "keyboards" case: case "MousePads": InvMgr.ReplenishInventory(enmInvParts.Keyboards); break; Now I'm finished. there is no need to change partsfactory or inventorymgr. this shows that I have successfully removed all remaining coupling issues caused by the switch statement inside partsfactory and that adding a new class requires minimal effort. Conclusion The concrete factory pattern is one of the simplest yet most powerful design patterns. because of its simplicity, the subtle coupling and cohesion implications that accompany the implementation you choose when applying the pattern are sometimes overlooked. indeed, it is not always possible or necessary to severely reduce coupling or completely maximize cohesion; however, you need to be mindful of their presence and their implications in whatever context you happen to apply this design pattern. |