PHP design pattern-share yuan pattern statement: This series of blog reference material "big talk design pattern", author Cheng Jie.
The shared object mode is used to minimize memory usage and share information with as many similar objects as possible. it is suitable for the use of a large number of objects that are unacceptable due to duplication. Some statuses of objects are usually shared. A common practice is to put them in an external data structure and pass them to the user when necessary.
UML class diagram:
Role Analysis:
FWFactory: creates and manages BlogModel objects.
All the specific shared element parent interface roles (BolgModel): accept the role and external status.
JobsBlog: a change that adds storage space for internal objects.
Code implementation:
";} Function showColor () {echo"Jobs
";}}/** Leijun blog template * Class LeiJunBlog */class LeiJunBlog implements IBlogModel {function showTime () {echo" Beijing Time: 17 o'clock
";} Function showColor () {echo"Lei Jun
";}}/** Blog template factory * Class BlogFactory */class BlogFactory {private $ model = array (); function getBlogModel ($ name) {if (isset ($ this-> model [$ name]) {echo "I am in the cache
"; Return $ this-> model [$ name];} else {try {echo" I created
"; $ Class = new ReflectionClass ($ name); $ this-> model [$ name] = $ class-> newInstance (); return $ this-> model [$ name];} catch (ReflectionException $ e) {echo "the object you requested cannot be created.
"; Return null ;}}}}
Client call code:
Header ("Content-Type: text/html; charset = utf-8"); // ------------------------ test code in facade mode ------------------ require_once ". /Flyweight. php "; $ factory = new BlogFactory (); $ jobs = $ factory-> getBlogModel (" JobsBlog "); if ($ jobs) {$ jobs-> showTime (); $ jobs-> showColor () ;}$ jobs1 = $ factory-> getBlogModel ("JobsBlog"); if ($ jobs1) {$ jobs1-> showTime (); $ jobs1-> showColor () ;}$ leijun = $ factory-> getBlogModel ("LeiJunBlog"); if ($ leijun) {$ leijun-> showTime (); $ leijun-> showColor () ;}$ leijun1 = $ factory-> getBlogModel ("LeiJunBlog"); if ($ leijun1) {$ leijun1-> showTime (); $ leijun1-> showColor () ;}$ aFanda = $ factory-> getBlogModel ("aFanda"); if ($ aFanda) {$ aFanda-> showTime (); $ aFanda-> showColor ();}
Advantages:
1. reduce the number of running object instances and save memory
2. centrally manage the statuses of many "virtual" objects
Disadvantages:
Once implemented, a single logical implementation cannot have independent and different behaviors.
Applicable scenarios:
When a class has many instances and these instances can be controlled by the same method, we can use the metadata mode.
PHP object-oriented design model