Simple factory mode (also known as static factory mode), a simple factory produces finished products, while hiding the details of the products produced by the client. Define a product interface during implementation, and establish a finished product through a specific static method. Suppose there is a music box factory. The guest who buys the music box does not need to know how to make the music box. He only needs to know how to play the music box. The above concepts are represented by the UML class diagram: As shown in, musicboxdemo represents the customer's role. It only depends on the imusicbox interface, but does not care about the specific implementation. The actual generation of imusicbox instances is completed by musicboxfactory, use a simple program to implement the above UML class diagram:
Public interface imusicbox { Public void play (); }
Public class pianobox implements imusicbox { Public void play (){ System. Out. println ("playing piano music "); } }
Public class violinbox implements imusicbox { Public void play (){ System. Out. println ("playing violin music ^_^ "); } }
public class musicboxfactory { Public static imusicbox createmusicbox (string name) throws instantiationexception, illegalaccessexception, classnotfoundexception { // here, the Java reflection mechanism is used to generate instances. // However, the client does not need to worry about it. // it will be changed later. the program here, client programs do not need to be changed return (imusicbox) class. forname (name ). newinstance (); }< BR >}
Public class musicboxdemo { Public static void main (string [] ARGs) throws exception { Playmusicbox (musicboxfactory. createmusicbox ("ianobox ")); Playmusicbox (musicboxfactory. createmusicbox ("violinbox ")); }
Public static void playmusicbox (imusicbox musicbox ){ Musicbox. Play (); } } Because the client only depends on the imusicbox interface, even if you change the implementation method in createmusicbox () in the future, it has no impact on the client. Let's take a look at the class structure of simple factory: As long as the customer faces the factory, the customer depends on the product interface, and the specific product implementation can be separated from the customer, they can also be switched. |