Flyweight mode in design mode Flyweight mode

xiaoxiao2021-03-06  74

Flyweight mode definition: Avoid a large number of small costs of small classes (such as spending memory), allowing you to share a class (category).

Why use? The principle of object-oriented language is that everything is an object, but if you really use, sometimes the number of objects may be very large, such as word processing software, if each text is used as an object, thousands of words, objects The number is thousands, undoubtedly spent memory, then we still have to "seek to deposit", find the common point of these object groups, design a category, package can be shared, and some features depends on the application (Context ), Is unsuitable, this is also two important concepts in Flyweight Internal state Intrinsic and external status Extrinsic points.

To put the white point, it is first pinching a raw model, and then the specific model of each character is produced, it is clear that different new objects are required here, so Factory mode often appears in the Flyweight mode .flyweight The internal status is used to share, Flyweight Factory is responsible for maintaining a Flyweight Pool to store objects in the internal state.

Flyweight mode is an improved program efficiency and performance mode, which will greatly speed up the running speed of the program. Applications a lot: such as reading a series of strings from a database, there are many repetitions in these strings, then we These strings can be stored in the Flyweight pool (Pool).

how to use?

Let's start with the Flyweight abstraction interface:

Public interface flyweight {public void Operation (EXTRINSICSTATE STATE);} // Appreciation data type (self-design) public interface extrinsicState {}

Below is a concreteflyweight, increasing memory space for internal status, and ConcreteflyWeight must be shared. Any state it saves must be internal (Intrinsic), that is, ConcreteFlyWeight must be in combination with it. Not related.

Public Class ConcreteflyWeight Implements Flyweight {Private IntrinsicsTate State; Public Void Operation (ExtrinsicsTate State) {// Specific Operation}}

Of course, not all Flyweight specific implementation subclasses need to be shared, so there is another non-shared Concreteflyweight:

Public Class UnsharedConcreteflyweight Implements Flyweight {Public Void Operation (ExtrinsicState State) {}}

FlyWeight Factory is responsible for maintaining a FlyWeight pool (stores internal state), when the client requests a shared flyweight, this factory first searches if there is already available in the pool. If there is, Factory just simply returns this object, otherwise, create a New objects, add to the pool, return to send this object. Pool

public class FlyweightFactory {// Flyweight pool private Hashtable flyweights = new Hashtable (); public Flyweight getFlyweight (Object key) {Flyweight flyweight = (Flyweight) flyweights.get (key); if (flyweight == null) {// create new Concreteflyweight flyweight = new contReteflyWeight (); flyweights.put (key, flyweight);}}}

Thus, the basic framework of the Flyweight pattern already in place, we look at how call: FlyweightFactory factory = new FlyweightFactory (); Flyweight fly1 = factory.getFlyweight ( "Fred"); Flyweight fly2 = factory.getFlyweight ( "Wilma"); .. ....

From the call, it seems to be a pure Factory, but the mystery is in the internal design of Factory.

FlyWeight mode Apply in the data source such as XML, we have mentioned above, when reading a string from the data source, there is definitely, then we can use the Flyweight mode to improve efficiency, with a record CD as an example, in an XML In the file, multiple CDs are stored.

Each CD has three fields: 1. Caver dates (YEAR) 2. Singer name and other information (Artist) 3. Record track (title)

Among them, the name of the singer may be repeated, that is, there may be a number of different tracks of different tracks of the same singer. We will "sing" as a shared concreteflyweight. Other two fields as UnsharedConcreteflyweight.

First look at the contents of the data source XML file:

another green world </ title> <year> 1978 </ year> <artist> ENO, Brian </ artist> </ cd> <CD > <title> Greatest Hits </ Title> <Year> 1950 </ year> <artist> Holiday, billie </ artist> </ cd> <cd> <title> taking tiger mountain (by strategy) </ title> < Year> 1977 </ year> <artist> ENO, Brian </ artist> </ cd> ....... </ color></p> <p>Although only 3 of the examples above, CDs can be seen as a large number of duplicate small classes because there are only three fields, and there are repetitive (singers name).</p> <p>The CD is similar to the above interface flyweight:</p> <p>public class CD {private String title; private int year; private Artist artist; public String getTitle () {return title;} public int getYear () {return year;} public Artist getArtist () {return artist;} public void setTitle ( String t) {title = t;} public void setYear (int y) {year = y;} public void setartist (artist a) {artist = a;}}</p> <p>Will "Singer Name" as a shared Concreteflyweight:</p> <p>Public class artist {// internal status private string name; // Note That artist is immutable. String getName () {return name;} artist (string n) {name = n;}}</p> <p>Look Flyweight factory, designed to be shared by the above manufacturing ConcreteFlyweight: Artistpublic class ArtistFactory {Hashtable pool = new Hashtable (); Artist getArtist (String key) {Artist result; result = (Artist) pool.get (key) Generate new Artist if (Result == null) {result = new artist (key); pool.put (key, result);} return result;}}</p> <p>When you have thousands of or even more CDs, the Flyweight mode saves more space, the more Flyweight, the more space saves, the greater the space.</p></div><div class="text-center mt-3 text-grey"> 转载请注明原文地址:https://www.9cbs.com/read-93069.html</div><div class="plugin d-flex justify-content-center mt-3"></div><hr><div class="row"><div class="col-lg-12 text-muted mt-2"><i class="icon-tags mr-2"></i><span class="badge border border-secondary mr-2"><h2 class="h6 mb-0 small"><a class="text-secondary" href="tag-2.html">9cbs</a></h2></span></div></div></div></div><div class="card card-postlist border-white shadow"><div class="card-body"><div class="card-title"><div class="d-flex justify-content-between"><div><b>New Post</b>(<span class="posts">0</span>) </div><div></div></div></div><ul class="postlist list-unstyled"> </ul></div></div><div class="d-none threadlist"><input type="checkbox" name="modtid" value="93069" checked /></div></div></div></div></div><footer class="text-muted small bg-dark py-4 mt-3" id="footer"><div class="container"><div class="row"><div class="col">CopyRight © 2020 All Rights Reserved </div><div class="col text-right">Processed: <b>0.033</b>, SQL: <b>9</b></div></div></div></footer><script src="./lang/en-us/lang.js?2.2.0"></script><script src="view/js/jquery.min.js?2.2.0"></script><script src="view/js/popper.min.js?2.2.0"></script><script src="view/js/bootstrap.min.js?2.2.0"></script><script src="view/js/xiuno.js?2.2.0"></script><script src="view/js/bootstrap-plugin.js?2.2.0"></script><script src="view/js/async.min.js?2.2.0"></script><script src="view/js/form.js?2.2.0"></script><script> var debug = DEBUG = 0; var url_rewrite_on = 1; var url_path = './'; var forumarr = {"1":"Tech"}; var fid = 1; var uid = 0; var gid = 0; xn.options.water_image_url = 'view/img/water-small.png'; </script><script src="view/js/wellcms.js?2.2.0"></script><a class="scroll-to-top rounded" href="javascript:void(0);"><i class="icon-angle-up"></i></a><a class="scroll-to-bottom rounded" href="javascript:void(0);" style="display: inline;"><i class="icon-angle-down"></i></a></body></html><script> var forum_url = 'list-1.html'; var safe_token = '6XCh_2FTD4RBUOyfSb3UV5_2B3QBT5gLTjj0cRqRm31K75eyvD59XvZP2V_2F0em5GZAOlF1UilHHnkPjrMq0P'; var body = $('body'); body.on('submit', '#form', function() { var jthis = $(this); var jsubmit = jthis.find('#submit'); jthis.reset(); jsubmit.button('loading'); var postdata = jthis.serializeObject(); $.xpost(jthis.attr('action'), postdata, function(code, message) { if(code == 0) { location.reload(); } else { $.alert(message); jsubmit.button('reset'); } }); return false; }); function resize_image() { var jmessagelist = $('div.message'); var first_width = jmessagelist.width(); jmessagelist.each(function() { var jdiv = $(this); var maxwidth = jdiv.attr('isfirst') ? first_width : jdiv.width(); var jmessage_width = Math.min(jdiv.width(), maxwidth); jdiv.find('img, embed, iframe, video').each(function() { var jimg = $(this); var img_width = this.org_width; var img_height = this.org_height; if(!img_width) { var img_width = jimg.attr('width'); var img_height = jimg.attr('height'); this.org_width = img_width; this.org_height = img_height; } if(img_width > jmessage_width) { if(this.tagName == 'IMG') { jimg.width(jmessage_width); jimg.css('height', 'auto'); jimg.css('cursor', 'pointer'); jimg.on('click', function() { }); } else { jimg.width(jmessage_width); var height = (img_height / img_width) * jimg.width(); jimg.height(height); } } }); }); } function resize_table() { $('div.message').each(function() { var jdiv = $(this); jdiv.find('table').addClass('table').wrap('<div class="table-responsive"></div>'); }); } $(function() { resize_image(); resize_table(); $(window).on('resize', resize_image); }); var jmessage = $('#message'); jmessage.on('focus', function() {if(jmessage.t) { clearTimeout(jmessage.t); jmessage.t = null; } jmessage.css('height', '6rem'); }); jmessage.on('blur', function() {jmessage.t = setTimeout(function() { jmessage.css('height', '2.5rem');}, 1000); }); $('#nav li[data-active="fid-1"]').addClass('active'); </script>