Prototype mode:
1 prototype Mode2 Overview3 Use the prototype instance to specify the kind of object to create and create a new object by copying the prototypes. 4 5 Applicability6 1. When a system should be independent of its product creation, composition, and presentation. 7 8 2when the class to instantiate is specified at run time, for example, by dynamic loading. 9 Ten 3to avoid creating a factory class hierarchy that is parallel to the product class hierarchy. One A 4. When an instance of a class can have only one of several different state combinations. - - building the corresponding number of prototypes and cloning them may be more convenient than manually instantiating the class each time you use the appropriate state. the - participants - 1. Prototype - declares an interface for a clone itself. + - 2. Concreteprototype + implements the operation of a clone itself. A at 3. Client -Let a prototype clone itself to create a new object.
Test class:
1 Public classTest {2 3 Public Static voidMain (string[] args) {4Prototype Pro =NewConcreteprototype ("Prototype");5Prototype Pro2 =(Prototype) Pro.clone ();6 System.out.println (Pro.getname ());7 System.out.println (Pro2.getname ());8 }9 Ten}
1 /**2 * Declares a clone's own interface3 * @author 4 *5 */6 Public classPrototypeImplementscloneable {7 8 PrivateString name;9 Ten Public voidsetName (String name) { One This. Name =name; A } - - PublicString GetName () { the return This. Name; - } - - PublicObject Clone () { + Try { - return Super. Clone (); +}Catch(Exception e) { A e.printstacktrace (); at return NULL; - } - } -}
1 /**2 * Implement a clone of its own operation3 * @author 4 *5 */6 Public classConcreteprototypeextendsPrototype {7 8 PublicConcreteprototype (String name) {9 setName (name);Ten } One}
Java design pattern-creation mode-prototype mode