Design Mode-simple factory Mode
Simple factory mode in Design Mode
Reading and learning the design mode. The source of the book is "big talk design mode". How to Design the program?
In the book "big talk", the simple factory model is illustrated by using a calculator as an example. In fact, it is the simplest interface-oriented programming thinking, which does not depend on specific implementations, but focuses on interfaces. This is an important shift in thinking.
Important:
1. Perform inheritance to create a multi-state attribute, and then implement the interface of the parent class in the subclass to implement different interfaces in different subclasses. It is interesting to directly call the implemented interface method to get the final value.
2. Add code to change the demand without modifying the previous one.
3. The most popular saying is high cohesion and low coupling!
Look at my own factory calculator"
Import java. io. bufferedReader; import java. io. IOException; import java. io. inputStreamReader; public class factory {private final String PLUS = "+"; private final String SUB = "-"; private final String RIDE = "*"; private final String DIVIDE = "/"; public factory () throws IOException {BufferedReader strin = new BufferedReader (new InputStreamReader (System. in); System. out. print ("input number:"); String str = strin. rea DLine (); BufferedReader strin2 = new BufferedReader (new InputStreamReader (System. in); System. out. print ("input operator number:"); String str2 = strin2.readLine (); Operation op = GetOperation (str2); BufferedReader strin3 = new BufferedReader (new InputStreamReader (System. in); System. out. print ("input number:"); String str3 = strin3.readLine (); System. out. println ("Result:" + op. getResult (Float. valueOf (str), Float. valueOf (str3 )) );} Private Operation GetOperation (String sign) {switch (sign) {case PLUS: return new SHA_plus (); case SUB: return new SHA_sub (); case RIDE: return new SHA_ride (); case DIVIDE: return new SHA_divide ();} return null;} public static void main (String [] args) {try {new factory ();} catch (IOException e) {e. printStackTrace () ;}} interface Operation {float A = 0; float B = 0; abstract float getResult (float A, float B) ;} Class SHA_plus implements Operation {@ Overridepublic float getResult (float A, float B) {return A + B;} class SHA_sub implements Operation {@ Overridepublic float getResult (float, float B) {return A-B;} class SHA_ride implements Operation {@ Overridepublic float getResult (float A, float B) {return A * B ;}} class SHA_divide implements Operation {@ Overridepublic float getResult (float A, float B ){ If (B! = 0) {return A/B;} else return 0 ;}}