Yesterday I looked at the design pattern, reviewed the simple factory model, made a note, a brief discussion of my understanding of the simple factory model. The book is used in C #, because I am learning Java, so I implemented it with Java. If there is a wrong place to speak, hope to be able to point out. Simple factory design mode can simply be understood as, you take an empty pocket to the fruit shop to buy fruit, you put an empty bag to the fruit shop owner, and then told the boss I need a bag of grapefruit, 10 minutes later. The boss handed you a bag of grapefruit. You don't need to know how they differentiate between grapefruit and oranges, and how to put grapefruit in a bag. You just need to know that you went to the fruit shop and told him you needed a bag of grapefruit.
The code can be simply understood as, fruit shop, fruit and grapefruit three parts. If you do not talk about user interface, you can directly contact with the fruit shop, the following code can be understood as a fruit shop, used to create fruit. You can tell him what kind of fruit you need and he will return you a bag of fruit.
Public classFruitsfactory { Public StaticFruit createfruit (String name) {Fruit Fruit=NULL; Switch(name) { CaseGrapefruit: Fruit=Newgrapefruit (); Break; CaseOrange: Fruit=NewTangerine (); Break; } returnfruit; }}
The following class is an abstract class that can be understood as the fruit of the general term, fruit shop inside all the fruit mix.
Public Abstract classFruit {protected Doubleweight; Public Doublegetweight () {returnweight; } Public voidSetweight (Doubleweight) { This. Weight =weight; } Public Abstract voidGetResult ();}
Here is the concrete implementation of the specific fruit, abstract class.
public class grapefruit extends Fruit { private double price=5.5; @Override public void GetResult () {System.out.println () The price of a bag of grapefruit is:" + (Weight*price)); }}
Public class extends Fruit { privatedouble price=3.5; Public void GetResult () { System.out.println ("The price of a bag of oranges is:" + (weight*); }}
The simple factory model can be divided into such parts, his greatest benefit can be understood as, if the fruit shop in the new lemon, you just need to create a new lemon, and then in the fruit store switch inside the branch is enough, not to modify the other code. Does it feel like there's a lot less correlation between the codes? This will be more conducive to post-maintenance code.
Java implements simple Factory mode