The abstract factory mode provides an interface for creating a series of related or mutually dependent objects. The key point of using the abstract factory mode is to cope with the demand changes of "Multi-series object creation. In a word, you will understand the abstract factory model.OOPEssence:API-oriented programming.
After reading the terrylee example, I added
Define two abstract classes first
Public Abstract Class Tax
{
Public Abstract Double Gettax ();
}
Public AbstractClassBonus
{
Public Abstract DoubleGetbonus ();
}
Why define these two classes?
A well-maintained system should follow the "open and closed principle ". That is, to close the originalCodeOpen the extension to the original code (such as class inheritance, interface implementation)
This is equivalent to defining two interfaces which can be inherited by any business.
Rewrite the methods of these two abstract classes:
Code
Public Class Mytax: Tax
{
Public Override Double Gettax ()
{
Return 4000 ;
}
}
Public Class Mybonus: bonus
{
Public Override Double Getbonus ()
{
Return 214.3 ;
}
}
To facilitate calls to different business switches, we need a factory. Of course we can abstract it out.
Public Abstract Class Abstractfacory
{
Public Abstract Tax createtax ();
Public Abstract Bonus createbonus ();
}
At this time, we can feel the benefits of defining two abstract classes: tax and bouns.
Implement our own class
Code
Public Class Myfactory: abstractfacory
{
Public Override Tax createtax ()
{
Return New Mytax ();
}
Public Override Bonus createbonus ()
{
Return New Mybonus ();
}
}
Of course, we need to know which factory method to instantiate. The best way to do this is to use the reflection mechanism, because it provides code concealment. You only need to modify the configuration file.
Modify the abstract factory and add a static method to instantiate the factory. Of course, they can also be independent.
Code
Public Abstract Class Abstractfacory
{
Public Static Abstractfacory getinstance ()
{
Return (Abstractfacory) Assembly. Load ( " Myabstractfactory " ). Createinstance ( " Myabstractfactory. myfactory " );
}
Public AbstractTax createtax ();
Public AbstractBonus createbonus ();
}
Client call:
Abstractfacory af = Abstractfacory. getinstance ();
Double GZ = Af. createtax (). gettax ();
Double Jj = Af. createbonus (). getbonus ();
In this way, the client only depends on the abstract class and does not care about other things.
For example, to add a new business, you only need to add two new business rules newtax, newbonus, and newfactory.
the most important thing is that the addition or modification does not affect other services.