1. Java design mode serialization (1) --- factory method mode
Intent:
Defines an interface used to create objects, so that the subclass determines which class to instantiate. Factory method delays the instantiation of a class to its subclass.
Applicability:
- When a class does not know the class of the object it must create.
- When a class wants its subclass to specify the object it creates.
- When a class delegates the responsibility of creating an object to one of multiple help sub-classes, and you want to localize the information of which help sub-classes are proxies.
Instance:
1. Define a factory interface for clothes production
package Factory_Method_Pattern;public interface ClothesFactory { public Clothes productClothes(); }
2. Implement the interface of this clothing factory to define the type of clothes to be produced.
package Factory_Method_Pattern;public class AdultClothesFactory implements ClothesFactory {@Overridepublic Clothes productClothes() { return new AdultClothes();}}
package Factory_Method_Pattern;public class ChildClothesFactory implements ClothesFactory {@Overridepublic Clothes productClothes() { return new ChildClothes();}}
3. Define clothes interface (clothes are used for clothing)
package Factory_Method_Pattern;public interface Clothes{ public void dressClothes();}
4. Clothes interface, clothes, and people
Package factory_method_pattern; public class adultclothes implements clothes {@ overridepublic void dressclothes () {system. Out. println ("clothes produced by a friend Clothes Factory, wear by a friend ");}}
Package factory_method_pattern; public class childclothes implements clothes {@ overridepublic void dressclothes () {system. Out. println ("clothes produced by children's clothing factory, children wear ");}}
5. Test this mode.
package Factory_Method_Pattern;public class Test{ public static void main(String[] args){ ClothesFactory clothesFactory = new ChildClothesFactory(); clothesFactory.productClothes().dressClothes(); ClothesFactory adultClothesFactory = new AdultClothesFactory(); adultClothesFactory.productClothes().dressClothes(); }}
6. Thank you for browsing. Thank you for choosing axe.