EXTENSIBLE Applications: New Features without Recompiling

xiaoxiao2021-03-06  50

Joe Wirtley

In this article, Joe Wirtley describes an architecture for your applications that allows you to add new features without recompiling. Using reflection, interfaces, and dynamically loaded assemblies, you can create applications that can easily be extended with new business logic.

Imagine that you've been given the task of writing an order entry application for Widgets R Us. Widgets R Us sells its widgets to other corporations resell those widgets. Most of its business comes from a few large customers, and the pricing rules can that Vary Dramatically Among Customers. Because The Rules Vary by Customer, The Company Hasn't Found An off-the-shelf Application To Accommodate ITS Requirements.

The two largest Widgets R Us customers are Acme and Megacorp. Acme gets a discount of 10 percent off the standard price when the current time is on an even minute and 15 percent off when it's on an odd minute. If Acme orders more than five widgets , it gets an additional 5 percent discount. For Megacorp, the price is based on the sale type. For resale, there's a 20 percent discount. For corporate sales, there's a 10 percent discount. Government sales are at a 10 percent premium, and Other Sales Are At the List Price. I'm Sure You've Seen Business Rules with Similarly Screwy Logic in Your Own Projects!

This description implies two requirements:. First, since you can not anticipate the design of new customer pricing rules, you should place no restrictions on new pricing algorithms Second, you may need to collect extra information to price an order For example, to. Price a megacorp order, you need to know the sales.

DESIGN

You need to accommodate custom pricing rules based on a customer, but you do not want to change the order entry application each time you get a new customer So you need to apply one of the most basic software design principles:. Separation of concerns. Since you want the order entry application to remain the same while customer order pricing rules change, you need to separate the order entry software from the customer order pricing software.But you can not completely separate them, for two reasons. First, the order entry application collects the information needed to price the order. Second, the order entry application must have a way of getting a price for an order, so it needs a way to interact with the customer pricing software. Since you do not want to link the order entry application directly to the customer pricing rules, you need to create a piece of software to serve as an intermediary between the two. This allows you to change either the order entry application or the customer pri CING WITHOUT CHENGING The Other.

Figure 1 is an abstract representation of these three pieces of software. In this figure, I use the word interface in the most abstract sense. I do not mean a C # interface. I simply mean that there's some software that's separate from both the order Entry Application and The Customer Pricles, But Is Relied on by Both.

To support variations in customer order pricing, the pricing algorithm for each customer will be stored in a separate assembly. To load these assemblies dynamically, I've defined a dynamic package class. Each instance of the dynamic package class encapsulates a dynamically loaded assembly. Every dynamic package has a builder that's responsible for creating objects from that dynamic package.If Figure 1 is the design view from 10,000 feet, the UML component diagram in Figure 2 shows the view from 5,000 feet. in this diagram, each component represents a separate .NET assembly and corresponds to a project in the .NET solution. The two assemblies within the box labeled Interface correspond to the Interface cloud in Figure 1. The OrderEntry component represents the order entry application. The Acme, Megacorp, and Generic components represent the Oval Labeled Pricing in Figure 1. In this Component Diagram, The Dashed Lines Denote Dependencies, with the arrow pointing in the direction of the d ependency. For example, the line from the Acme component to the OrderEntryCommon component means that the Acme component depends on the OrderEntryCommon component. You'll notice in this diagram that all of the dependencies from the client pricing assemblies and the order entry application go toward . This is the company.

Interface code

. This section shows the code for the interface defined in the previous section There are two things that the interface software must provide: a means to exchange order information, and a means of interaction between order entry and pricing.

As the method to share order information, I've defined an order class. The following code is shared between the order entry application and the customer-specific dynamic assemblies. Note that for the purpose of this example, there's only one item on the order , So The Color and Quantity Properties Are On The Order Itself, Rather Than A Separate Line Item Class.Public Class Order {

Public order () {

}

Public int quantity;

Public WidgetColor Color;

Public Double Price;

}

Public enum widgetcolor {

Blue = 1,

RED = 2,

White = 3,

Yellow = 4

}

The following code shows the interface definitions shared between the order entry application and the customer-specific dynamic assemblies. These three interfaces enable the order entry application to interact with customer-specific pricing and are defined in the CustomerPackageInterfaces assembly.

Public interface iorderpricing {

Void Price (Order ORDER);

}

IOrderPricing has one method to calculate the price of an order, and receives the order as a parameter The calculated price is written to the price property of the order passed as a parameter;. Therefore, there's no return value from this method.

IOrderDataControl is meant to be implemented by a control that captures customer-specific order information. It has methods to read data from an order to the control and to write data to an order from the control. It also has a method that the order entry application Uses to pass a delegate to be Called WHEN A Value Changes in The Control To Capture Customer-Specific Information.

Public interface iorderdatacontrol {

Void ReadorderData;

Void WriteRDATA (Order ORDER);

Void setorderchangeeevent (eventhandler handler);

The ICustomerPackageBuilder interface is for the builder class. Each dynamic package must implement a builder class that's responsible for creating objects from that package. This interface defines methods to create objects that implement the IOrderPricing and IOrderDataControl interfaces and to return a new order object. I allow each customer package to create a new order instance because there may be order properties that are specific to a customer. The GetOrderDataControl method returns a control that can be placed on a form that will gather the customer-specific order information. lastly, the GetOrderPricing method Returns An Object To Calculate The Price for An ORDER, Which Can Also Be Specific To a Customer.

Public Interface IcustomerPackageBuilder:

IPackageBuilder {

IORDERPRICING GETORDERPRICING ();

Control getorderDataControl ();

ORDER NEWORDER ();

}

Note That The iCustomerPackageBuilder Class Inherits The iPackageBuilder Interface, Which Makes It Compatible with the DynamicPackage Class Described Later.

ORDER Entry ApplicationThe Windows in

Figure 3 and

Figure 4 are from the order entry application. As you can see, this is a greatly simplified prototype of an order entry system. You can enter a customer, the color, and the quantity of widgets you want to order, and the application displays the .

Figure 4 Shows The Screen for a Megacorp Order. Note The Addition of The Sale Type Combo Box, Which Is Necessary to Price A Megacorp Order.

Listing 1 contains the relevant code from the order entry form. The first thing to note is that the form has a property to hold an instance of an order. It also has properties to refer to objects implementing the IOrderPricing interface and the IOrderDataControl interface, which Are used in profing the order.listic 1. Order entry form.

Private Order ORDER;

Private iORDERPRICING Pricing;

Private iorderdataControl CustomerOrderdata;

Private Void Calculateprice (Object Sender,

System.Eventargs e) {

IF (ORDER! = null) {

Order.color = (WidgetColor)

Cbocolor.selectedIndex 1;

ORDER.quantity = Convert.Toint32 (

TXTQUANTITY.VALUE);

IF (CustomerOrData! = null) {

// if there is a customer specific control,

// give it a chance to write its data to

// the order.

CustomerORDATA.WRITEORDERDATA (ORDER);

}

// Price the Order

Pricing.PriceOrder (Order);

LBLPRICE.TEXT =

Order.price.toString ("$ 0.00");

}

}

Private void ChangeCustomer (Object Sender,

System.Eventargs e) {

String Customer = CBOCUSTOMER.TEXT;

IDynamicpackage package;

Icustomerpackagebuilder Builder;

Control Customerspect;

// Get The Dynamic Package for The Customer.

// this Would PROBABLY BE DATA Driven

// IN a production impLementation.

Package = DynamiCKage.getDynamicPackage (

Customer);

Builder = package.builder as

Icustomerpackagebuilder;

Order = builder.neWorder ();

Pricing = builder.getORDERPRICING ();

CustomerspecificControl =

Builder.GetorderDataControl ();

// Take Care of The Customer Specific Control

Pnlcustomerspecific.Controls.clear ();

IF (CustomerspecificControl! = null) {

CustomerORDERDATA = CustomerspecificControl

As iorderdataacontrol; // read Any data in the order oto the customer

// Control

CustomerRorderData.ReadorderData (Order);

// Display the Control

Pnlcustomerspecific.controls.add (

CustomerspecificControl);

// Give the control company u al alPRICE To Call

//hen anything change

CustomerRorderData.setorderChangeevent (

New EventHandler (this.calculateprice);

} else {

CustomerOrderData = NULL;

}

// force a price calculation

Calculateprice (NULL, NULL);

}

The CalculatePrice method calculates the order price and is called whenever a value on the order entry form changes. The method first sets the values ​​of the color and quantity fields on the order instance from the values ​​on the form. The customerOrderData field is only assigned if there's customer-specific data being collected for an order. If the customerOrderData instance is not null, then CalculatePrice assigns any data from the customer-specific control to the order by calling the WriteOrderData method. CalculatePrice then calculates the price of the order by calling .

When the order entry user changes the customer on the order entry form, the application executes the ChangeCustomer method. The first function the ChangeCustomer method performs is to get the dynamic package for the customer name in the combo box on the order entry form. For illustration purposes, this order entry application loads an assembly with the exact name from the customer combo box. In a production application, you'd likely create a data-driven mapping between customers and assemblies, which would allow you to add new customers and assemblies without any change to the order entry application.Using the builder from the dynamic package, ChangeCustomer creates an order instance. It then gets an IOrderPricing reference and creates a control to gather customer-specific order information. Deferring the creation of these objects to the dynamic assembly IS critical in allowing additional functionality to be added by customer-specific assembly, for example, a megacorp Order Must Have .

Because there may be customer-specific order information collected, the order entry form has a panel to hold customer-specific data entry controls. The Sale Type combo box shown in Figure 4 is an example of a control using this panel. The ChangeCustomer method clears the controls from this panel every time the customer changes. If there's a control returned from the customer-specific dynamic package, that control is added to the panel. The control is also saved in the customerOrderData field, since the control implements the IOrderDataControl interface that allows data to be written to and read from the control. This interface is called before the customer-specific control is displayed to allow it to read data from the order. This is also the interface called in the CalculatePrice method to save data from the customer -Specific Control to the Order Before the price is cagculated. The Last Function Implement for the Customer-Specific Control Is To Pass An Event Handler To The ORDER-SPE Cific Control So That It Can Fire The CalculatePrice Method WHENEVER ANY Customer-Specific Order Data Changes.customer Pricles

In The Following Sections I'll show you how the profment assembly..

Generic Pricing

THE Gener Pricing for Widgets R US Orders Is Based On The Widget Color, AS Shown In The Following Code Fragment:

Public class orderpricles: iorderpricing {

Public void priceOrder (Order Order) {

Double priceeach = 0;

Switch (Order.color) {

Case WidgetColor.blue:

Priceeach = 1.00;

Break;

Case WidgetColor.Red:

Priceeach = 1.50;

Break;

Case WidgetColor.White:

PRICEEACH = 2.00;

Break;

Case widgetcolor.yellow:

Priceeach = 2.50;

Break;

}

Order.price = priceEach * order.quantity;

}

Acme Listing 2 contains all of the relevant code for pricing Acme orders. The first class defined is the builder class that's responsible for creating other objects from the assembly. The GetOrderPricing method returns an instance of the AcmeOrderPricing class that's also defined in Listing 2. Since for Acme there are no customer-specific fields required for order entry, the GetOrderDataControl method returns null. Likewise, since there's no extra order information for an Acme order, the NewOrder method returns an instance of the Order class.

The AcmeOrderPricing class is responsible for calculating the price of Acme orders. It applies the unusual rules for Acme after calculating the generic customer price for an order by calling the GenericCustomer PriceOrder method. For a customer with completely custom pricing, you would not need to Call the genericcustomer brings.

Listing 2. ACME ORDER Pricing.

Public Class Acmebuilder: icustomerPackageBuilder {

Public iorderpricing getorderpricing () {

Return new acmeorderpricing ();

}

Public control getorderdataacontrol () {

Return NULL;

}

Public order neworder () {

Return new Order ();

}

}

Public class acmeorderpricing: iorderpricing {

Public void priceOrder (Order Order) {

Double discount;

Genericcustomer.OrderPricing genericpricles =

New genericcustomer.OrderPricing ();

Generic Bricing.PriceOrder (Order);

// ACME GETS A 10% Discount from Standard

// ON Even Minutes and a 15% Discount ON

// odd minutes.

IF ((DATETIME.NOW.MINUTE% 2) == 0) {

Discount = 0.10;

} else {

Discount = 0.15;

}

// if They Order More Than 5, They Get

// AN Additional 0.5%

IF (Order.quantity> 5) {Discount = 0.05;

}

Order.price = (1 - discount) * ORDER.PRICE;

}

}

MEGACORP

Listing 3 shows the customer-specific pricing code for Megacorp. Similar to the Acme code, it has a builder class to create other objects from the assembly. Also like the Acme code, it contains the MegacorpOrderPricing class to handle the order pricing itself. Unlike the Acme code, the GetOrderDataControl method on the MegacorpBuilder class returns a new control instance, which I discuss later. This is because you need to collect the sale type to price a Megacorp order. This is also reflected in the MegacorpOrder class that's defined in this Listing. The megacorporder class address.................. ..

The MegacorpOrderPricing class calculates the price in a similar manner to the Acme calculation. It begins by calculating the generic price, and then applying an adjustment based on the sale type. The most interesting thing to note about the PriceOrder method is that the order passed as a parameter is typecast to the MegacorpOrder type. This typecast is necessary because you need the sale type to price an order for Megacorp. The typecast is possible because the order created by the NewOrder method on the builder is of the MegacorpOrder type.

Listing 3. Megacorp Order Pricing.

Public Class MegacorpBuilder:

IcustomerpackageBuilder {

Public iorderpricing getorderpricing () {

Return new megacorporderpricing ();

}

Public control getorderdataacontrol () {

Return new megacorporderControl ();

}

Public order neworder () {

Return new megacorporder ();

}

}

Public class megacorporderpricle: iorderpricing {public void priceOrder (ORDER Order) {

Genericcustomer.OrderPricing genericpricles =

New genericcustomer.OrderPricing ();

Generic Bricing.PriceOrder (Order);

// for megacorp, the price is based on the

// Sale Type

Switch ((Megacorporder) ORDER .saleType) {

Case SaleType.government:

Order.price = 1.1 * Order.price;

Break;

Case SaleType.Corporate:

Order.price = 0.9 * Order.price;

Break;

Case SaleType.resale:

Order.price = 0.8 * Order.price;

Break;

Case SaleType.other:

Break;

}

}

}

Public enum saLetype {

Government = 1,

Corporate = 2,

Resale = 3,

Other = 4

}

Public class megacorporder: ORDER {

Public megacorporder () {

SaleType = SaleType.other;

}

Public saLetype SaleType;

}

To price a Megacorp order, you must collect the sale type in addition to the base order information. In the assembly that defines the Megacorp order pricing, there's also a user control to collect the sale type. The user control has one combo box that allows the user to select the sale type as displayed in Figure 4. This control implements the IOrderDataControl interface, which allows it to interact with the order entry application The following code segment displays the implementation of this interface.:

Public void readorderdata (Order Order) {

Megacorporder CustomerOrder =

Megacorporder) Order;

SaleType SaleType = CustomerORDER.SALETYPE;

CbosaleType.SelectedIndex =

(int) SaleType - 1;

}

Public void writeorderdata (Order Order) {

Megacorporder CustomerOrder =

Megacorporder) Order;

CustomerORDER.SALETYPE =

(SaLetype) cbosaleType.selectedIndex 1;

}

Public void setorderchangeeevent (eventhandler handler) {

CbosaleType.Selected = Handler;

}

The ReadOrderData method is called by the order entry application when it wants to update the user control with data from an order object. It sets the SelectedIndex property on the Sale Type combo box based on the sale type of the order passed to the method. WriteOrderData handles the situation when the order entry application requests that the data from the user control be written to the order. lastly, the SetOrderChangeEvent method receives an EventHandler to be called whenever a value changes in the control. As you may remember, the order entry application passes in an event handler that fires the CalculatePrice method. in this control, I just set this handler to be called whenever the selected index changes on the Sale type combo box. This will force a price calculation whenever the sale type changes.

Dynamic Packages

The dynamic package class provides a convenient wrapper for dynamically loaded assemblies (see Listing 4) The dynamic package class has two public properties:.. Name and builder In this example, the name of the package is identical to the actual assembly name A more. advanced implementation might separate these two concepts to allow another level of redirection. The builder property represents the class responsible for creating objects from the dynamic assembly. It's possible to create objects from outside an assembly, but localizing object creation to the assembly itself simplifies coding.

Listing 4. Dynamic Package Class.

Public class dynamicpackage: idynamicpackage {

PRIVATE STRING NAME;

PRIVATEMBLY Assembly

Private iPackAGeBuilder Builder;

Static arraylist package = new arraylist (); public static idynamicpackage getDynamicPackage

String name) {

DynamicPackage Result = NULL;

Foreach (DynamiCKage P in

Dynamicpackage.pages {

IF (p.Name == name) {

Result = P;

Break;

}

}

IF (result == null) {

Result = New DynamiCKage (Name);

Packages.Add (Result);

}

Return Result;

}

Private Dynamickage (String Name) {

THIS.NAME = Name;

LOAD ();

}

PUBLIC STRING name {

Get {return name;}

}

Public iPackageBuilder Builder {

Get {returnal;}

}

PRIVATE VOID LOAD () {

// load the assembly and get the assembly object

askEMBLY = Getassembly (Name);

// Now Look for the packagebuilder

Builder = FINDBUILDER ();

}

Private iPackAGeBuilder Findbuilder () {

TYPE [] TYPES = askES ();

Foreach (Type T in Types) {

Type [] interfaces = t.findinterface

New Typefilter (InterfaceFilter), NULL;

IF (Interfaces.Length> 0) {

Constructorinfo constructorinfo =

T.GetConstructor (New Type [0]);

Return Constructorinfo.invoke

New Object [0]) AS iPackageBuilder;

}

}

Throw New Exception ("Cannot Find Builder IN"

"Dynamic Package" Name);

}

Private Static Bool InterfaceFilter (Type Type,

Object criteria) {

Return (Type == TypeOf (iPackageBuilder);

}

Private assembly getassembly (string name) {

AskEMBLY Assembly = NULL;

FOREACH (Assembly a in

Appdomain.currentDomain.getassemblies ()) {

IF (A.GetName (). name == name) {

askEMBLY = a;

Break;

}

}

IF (assembly == null) {

Try {

askMBLY = askFROMBLY.LOADFROM (Name

".dll");

} catCH {

Throw new Exception ("Cannot Load Dynamic" "Package" Name);

}

}

Return asmbly;

}

}

Note that the constructor for the DynamicPackage class is private. The only way to get an instance of the DynamicPackage class is to call the static GetDynamicPackage method. This method first looks through an ArrayList of all of the packages loaded thus far to see whether the requested .

When creating a dynamic package, the GetAssembly method first looks through the current AppDomain to see whether the requested assembly is already in memory. If it's not loaded, it loads it from disk using Assembly.LoadFrom, which takes a path name as a parameter. Depending On Your Specific Requirements, Other Static Methods of The Assembly Class Such as load or loadwithPartialname Could Be buy here.

Once the assembly is in memory, the FindBuilder method uses reflection to find a class in the loaded assembly that implements IPackageBuilder and returns an instance of that class. For each type defined in the assembly, it calls the FindInterfaces method. The FindInterfaces method takes a delegate, which it calls for each interface defined in the type. in this case, the delegate calls the InterfaceFilter method, which returns true if the interface is IPackageBuilder or a descendant of IPackageBuilder. Since the ICustomerPackageBuilder interface derives from IPackageBuilder, it will find classes That Implement iCustomerPackageBuilder.

When FindBuilder finds a type that supports IPackageBuilder, it gets the ConstructorInfo for the constructor with no parameters and uses that ConstructorInfo to create an instance of the type.ConclusionBy applying the design principle of separation of concerns and properly managing dependencies, you can create systems that easily accommodate change. This example shows an order entry application that can calculate the price for an order using a pricing method that may differ for every customer. and you can add unique pricing schemes for each customer without changing the code for the order entry application and .......................

Download 406WIRTLEY.ZIP

Sidebar: Why not take a data-driven approach?

You might be asking yourself, why not just create a data-driven implementation and avoid all of these classes? You could do that, but it would be much less flexible because it would force you to accommodate all future additions and changes in this data- driven implementation. It's far more important as a first step to design the appropriate interfaces than to worry about the implementation. Using the design described in this article, it would be quite straightforward to create a data-driven customer pricing assembly. in fact, it would be straightforward to create several different data-driven assemblies. Even in the circumstance where your current needs can be met through one data-driven algorithm, designing the correct interfaces allows you to add a hard-coded algorithm later if the need arises. But IF you begin with one data-driven algorithm without the appropriate interfaces, IT Would Be Much More Difficult To Go Back Later and Accommodate Sometting That Falls Outside of the Data-Dri Ven structure.to Find Out More About Hardcore Visual Studio and Pinnacle Publishing, Visit Their Web Site At http://www.pinpub.com/

Note: this is not a Microsoft Corporation Web Site. Microsoft Is Not Responsible for ITS Content.

转载请注明原文地址:https://www.9cbs.com/read-115512.html

New Post(0)