Money is the most lacking thing in silk. We provide a money-making factory for you to win.
Purpose: Define an interface used to create an object and let the subclass decide which class to instantiate. Factory Method delays the instantiation of a class to its subclass.
Applicability:
1. Money is made only when diaosi uses money
2. diaosi decides what to create, Grandpa Mao
Let's first look at a class chart.
1. Product
Defines the interface of the object created by the factory method.
2. ConcreteProduct
Implement the Product interface.
3. Creator
Declare the factory method. This method returns an object of the Product type.
4. ConcreteCreator
Redefines the factory method to return a ConcreteProduct instance.
<喎?http: www.bkjia.com kf ware vc " target="_blank" class="keylink"> VcD4KPHA + vt/fingerprint + PC9wPgo8cHJlIGNsYXNzPQ = "brush: java;"> package creatingtype. factorymethod; public interface Money {/*** print banknote */public void printMoney ();}
Package creatingtype. factorymethod; public interface MoneyFactory {/*** get Money */public Money getMoney ();}
Package creatingtype. factorymethod; public class BlueMoney implements Money {/*** print banknote */public void printMoney () {System. out. println ("You got a blue 50 yuan Grandpa Mao ");}}
Package creatingtype. factorymethod; public class BlueMoneyFactory implements MoneyFactory {/*** get Money */public Money getMoney () {return new BlueMoney ();}}
Package creatingtype. factorymethod; public class RedMoney implements Money {/*** print banknote */public void printMoney () {System. out. println ("You got a red 100 yuan Grandpa Mao ");}}
Package creatingtype. factorymethod; public class RedMoneyFactory implements MoneyFactory {/*** get Money */public Money getMoney () {return new RedMoney ();}}
Package creatingtype. factorymethod; // factory method mode public class MainClass {// The Factory method mode also belongs to the class creation mode and is also called the multi-state factory mode. The meaning of the factory method mode is to define a factory interface for creating // product objects and postpone the actual creation to the subclass. // The core factory class is no longer responsible for product creation. In this way, the core class becomes a // Abstract Factory role and is only responsible for the interfaces that must be implemented by specific factory subclass, // The advantage of further abstraction is that the factory method mode enables the system to introduce new products without modifying the specific factory role. Public static void main (String [] args) {// obtain BlueMoneyFactory MoneyFactory bmf = new BlueMoneyFactory (); // use BlueMoneyFactory to obtain the BlueMoney Instance Object Money bm = bmf. getMoney (); bm. printMoney (); // get RedMoneyFactory MoneyFactory rmf = new RedMoneyFactory (); // get the RedMoney Instance Object Money rm = rmf through RedMoneyFactory. getMoney (); rm. printMoney ();}}