Evgenii Legotckoi
Oct. 1, 2018, 2:34 p.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.

Do you like it? Share on social networks!

Comments

Only authorized users can post comments.
Please, Log in or Sign up
  • Last comments
  • Evgenii Legotckoi
    March 9, 2025, 9:02 p.m.
    К сожалению, я этого подсказать не могу, поскольку у меня нет необходимости в обходе блокировок и т.д. Поэтому я и не задавался решением этой проблемы. Ну выглядит так, что вам действитель…
  • VP
    March 9, 2025, 4:14 p.m.
    Здравствуйте! Я устанавливал Qt6 из исходников а также Qt Creator по отдельности. Все компоненты, связанные с разработкой для Android, установлены. Кроме одного... Когда пытаюсь скомпилиров…
  • ИМ
    Nov. 22, 2024, 9:51 p.m.
    Добрый вечер Евгений! Я сделал себе авторизацию аналогичную вашей, все работает, кроме возврата к предидущей странице. Редеректит всегда на главную, хотя в логах сервера вижу запросы на правильн…
  • Evgenii Legotckoi
    Oct. 31, 2024, 11:37 p.m.
    Добрый день. Да, можно. Либо через такие же плагины, либо с постобработкой через python библиотеку Beautiful Soup
  • A
    Oct. 19, 2024, 5:19 p.m.
    Подскажите как это запустить? Я не шарю в программировании и кодинге. Скачал и установаил Qt, но куча ошибок выдается и не запустить. А очень надо fb3 переконвертировать в html