Evgenii Legotckoi
Evgenii LegotckoiOct. 1, 2018, 4:34 a.m.

Structural Design Patterns - Adapt

Goals

  • Using sharing to effectively use a large number of objects.
  • Motif's GUI strategy to replace heavyweight widgets with lightweight widgets.

Problems

Designing objects down to the lowest levels of system "granularity" provides optimal flexibility, but can be prohibitively expensive in terms of performance and memory usage.


Discussion

The Flyweight pattern describes how to exchange objects so that their use can be implemented in fine detail without excessive overhead. Each Flyweight object is divided into two parts: a state-dependent (outer) part and a state-independent (inner) part. The internal state is stored (shared) in the Flyweight object. External state is stored or computed by client objects and passed to Flyweight when it is executed.

An illustration of this approach would be Motif widgets, which have been redesigned as lightweight widgets. While widgets are smart enough to work on their own; lightweight widgets exist in a dependent relationship with layout manager widgets. Each layout manager provides context-specific event handling, object management, and resource services for its lightweight widgets, and each lightweight widget is only responsible for context-independent state and behavior.

Structure

Flyweights are stored in the Factory repository. The client restrains itself from creating Flyweights directly and requests them from the Factory. Each flyweight object cannot stand on its own. Any attributes that might make sharing impossible must be provided by the client whenever a request for a Flyweight is made. If the context lends itself to "economy" (i.e., the client can easily calculate or find the required attributes), then the Flyweight pattern offers a context-appropriate result.

The Ant, Locust, and Cockroach classes can be "lightweight" because their concrete instance state has been de-encapsulated or externalized and must be provided by the client.

Example

Flyweight uses sharing to efficiently use a large number of objects. Modern web browsers use this technique to prevent the same images from being loaded twice. When a browser loads a web page, it looks at all the images on that page. The browser downloads all new images from the Internet and places them in an internal cache. For already loaded images, a flyweight object is created that has some unique data, such as position within the page.

Control List

  1. Verify that object overhead is an issue that needs attention and that the client of this class can correct the situation.
  2. Divide the state of the target class into: internal state and external state.
  3. Remove the external state from the class attributes and add a list of calling arguments for the affected methods to it.
  4. Create a factory that can cache and reuse existing class instances.
  5. The client should use the Factory instead of the new operator to query objects.
  6. The client must look up or compute state that is not internal to the object and provide that state to the methods of the class.

Rules of thumb

  • While Flyweight shows how to make many small objects, Facade shows how to make one object representing an entire subsystem.
  • Flyweight is often combined with Composite to implement common list nodes.
  • Terminal symbols in the interpreter's abstract syntax tree can be used as flyweights.
  • Flyweight explains when and how State objects can be shared.
We recommend hosting TIMEWEB
We recommend hosting TIMEWEB
Stable hosting, on which the social network EVILEG is located. For projects on Django we recommend VDS hosting.

Do you like it? Share on social networks!

Comments

Only authorized users can post comments.
Please, Log in or Sign up
AD

C ++ - Test 004. Pointers, Arrays and Loops

  • Result:50points,
  • Rating points-4
m

C ++ - Test 004. Pointers, Arrays and Loops

  • Result:80points,
  • Rating points4
m

C ++ - Test 004. Pointers, Arrays and Loops

  • Result:20points,
  • Rating points-10
Last comments
Evgenii Legotckoi
Evgenii LegotckoiOct. 31, 2024, 2:37 p.m.
Django - Lesson 064. How to write a Python Markdown extension Добрый день. Да, можно. Либо через такие же плагины, либо с постобработкой через python библиотеку Beautiful Soup
A
ALO1ZEOct. 19, 2024, 8:19 a.m.
Fb3 file reader on Qt Creator Подскажите как это запустить? Я не шарю в программировании и кодинге. Скачал и установаил Qt, но куча ошибок выдается и не запустить. А очень надо fb3 переконвертировать в html
ИМ
Игорь МаксимовOct. 5, 2024, 7:51 a.m.
Django - Lesson 064. How to write a Python Markdown extension Приветствую Евгений! У меня вопрос. Можно ли вставлять свои классы в разметку редактора markdown? Допустим имея стандартную разметку: <ul> <li></li> <li></l…
d
dblas5July 5, 2024, 11:02 a.m.
QML - Lesson 016. SQLite database and the working with it in QML Qt Здравствуйте, возникает такая проблема (я новичок): ApplicationWindow неизвестный элемент. (М300) для TextField и Button аналогично. Могу предположить, что из-за более новой верси…
k
kmssrFeb. 8, 2024, 6:43 p.m.
Qt Linux - Lesson 001. Autorun Qt application under Linux как сделать автозапуск для флэтпака, который не даёт создавать файлы в ~/.config - вот это вопрос ))
Now discuss on the forum
Evgenii Legotckoi
Evgenii LegotckoiJune 24, 2024, 3:11 p.m.
добавить qlineseries в функции Я тут. Работы оень много. Отправил его в бан.
t
tonypeachey1Nov. 15, 2024, 6:04 a.m.
google domain [url=https://google.com/]domain[/url] domain [http://www.example.com link title]
NSProject
NSProjectJune 4, 2022, 3:49 a.m.
Всё ещё разбираюсь с кешем. В следствии прочтения данной статьи. Я принял для себя решение сделать кеширование свойств менеджера модели LikeDislike. И так как установка evileg_core для меня не была возможна, ибо он писался…
9
9AnonimOct. 25, 2024, 9:10 a.m.
Машина тьюринга // Начальное состояние 0 0, ,<,1 // Переход в состояние 1 при пустом символе 0,0,>,0 // Остаемся в состоянии 0, двигаясь вправо при встрече 0 0,1,>…

Follow us in social networks