See a few times the abstract Factory mode, each view needs to be re-understood, it may be involved in a number of classes and interfaces, so more difficult to clear the relationship it! As far as I'm concerned, we still have to learn from our thoughts rather than mechanically.
Look at the class diagram:
Liar design mode-Class diagram
Look at the class diagram has been very chaotic, to simply comb under. We only look at the interface, so it is not difficult to see that the abstract factory is actually the production of abstract products, and concrete implementation is the implementation of the class to do.
Look at the specific demo:
Factory Floor
/** * Factory interface */ public interface ifactory { public Iuser CreateUser (); public idepartment createdepartment ();}
/** * MySQL factory */ public class mysqlfactory implements ifactory{@Override public Iuser CreateUser () { retu RN new Usermapper (); @Override public idepartment Createdepartment () { return new Span style= "COLOR: #000000" > Departmentmapper (); }}
/***/Publicclassimplements ifactory{ @Override public iuser CreateUser () { returnnew usermapper (); } @Override public idepartment createdepartment () { returnNew departmentmapper (); }}
Product Layer
/** * Departmental Layer interface */ public interface idepartment { public int
Savedepartment (Department Department); public idepartment getdepartment (int ID);}
/***/Publicinterface iuser {publicint saveuser (user user); Public Iuser getUser (int ID);}
/*** Departmental Data layer*/ Public classDepartmentmapperImplementsidepartment{@Override Public intsavedepartment (Department Department) {System.out.println ("Saved the department."); return1; } @Override PublicIdepartment Getdepartment (intID) {SYSTEM.OUT.PRINTLN ("Got a department."); return NULL; }}
/*** Role Data layer*/ Public classUsermapperImplementsIuser {@Override Public intsaveuser (user user) {System.out.println ("Save Uer"); return1; } @Override PublicIuser GetUser (intID) {SYSTEM.OUT.PRINTLN ("Get a user"); return NULL; }}
Client and entity classes
/***/Publicclass user{}
/***/Publicclass Department {}
/***/Publicclass Test {publicstatic void Main (string[] args) {// ifactory factory = new Mysqlfactory (); New sqlserverfactory (); = Factory.createuser (); Usermapper.getuser (Usermapper.saveuser (new User ()));} }
If we switch the database, we only need to switch the factory, the other code does not need to change.
The above is the author of the abstract Factory understanding, hope to help learn the small partner abstract factory!
Java Abstract Factory mode (Liar design mode)