Хранение кода в коллекции: TDictionary и анонимные методы.

Malcolm Groves, “Storing code in a collection : TDictionary and Anonymous Methods”, public translation into Russian from English More about this translation.

See also 13 similar translations

Translate into another language.

Participants

r3code744 points
Join Translated.by to translate! If you already have a Translated.by account, please sign in.
If you do not want to register an account, you can sign in with OpenID.
Pages: ← previous Ctrl next next untranslated
1 2 3

Storing code in a collection : TDictionary and Anonymous Methods

Хранение кода в коллекции: TDictionary и анонимные методы.

History of edits (Latest: r3code 2 years ago) §

In my earlier post, I mentioned you could use the new generic collection classes in Delphi 2009 to store anonymous methods instead of data. I wanted to try this out so I came up with the scenario of implementing factory classes as an excuse to experiment.

Ранее я упоминал, что Вы можете использовать новые классы универсальных коллекций в Delphi 2009, чтобы сохранить анонимные методы вместо данных. Я хотел проверить это, потому придумал сценарий реализации классов фабрики.

History of edits (Latest: r3code 1 year, 3 months ago) §

Factories can be a very useful way to centralise the creation logic for classes. Very often you see it when you have a base class and a whole bunch of different descendant classes and you want to do the creation in one place. Let’s say you have a reporting application. You may have a base report and a bunch of descendant reports, and you want to enforce some consistency over property values for the different reports that are set at the time of creation. Having these spread around every different place a report could be created may be error-prone. Alternatively, maybe you want to get away from the massive if…then..else blocks you often see in this situation. A Report Factory can give you one place to make sure all reports get created in the certain way, and also let the client code simply request a report by name and have the correct concrete report class created for them.

Фабрики могут быть очень полезны для централизации логики создания классов. Очень часто Вы видите это, когда у Вас есть базовый класс и целый набор различных классов-потомков, и Вы хотите создавать их в одном месте. Скажем, у Вас есть приложение для создания отчетов. У Вас может быть основной отчет и набор порожденных отчетов, и Вы хотите обеспечить некоторую согласованность по значениям свойств для различных отчетов, которые установлены во время создания. Помещение их во всех возможных местах создания очета, может привести к ошибкам. В качестве альтернативы, возможно, Вы захотите уйти от огромных if…then...else блоков, которые вы можете часто видеть в такой ситуации. Фабрика отчетов предоставит вам общее место, для того чтобы удостовериться, что все отчеты создаются првильным способом, а также позволит клиентскому коду просто запросить отчет по имени и получить надлежащий конкретный класс отчета, созданный для него.

History of edits (Latest: r3code 1 year, 3 months ago) §

Problem is usually this means writing a new factory each time you want this, plus creating factory mapping classes to register each concrete report. This is not only a whole bunch of effort and unnecessary classes, it’s more new code to debug.

Проблему обычно составляет необходимость писать новую фабрику каждый раз она вам понадобится, плюс создание связующих классов фабрики для регистрации каждого конкретного отчета. Это не только целая куча работы и ненужных классов, это еще больше нового кода для отладки.

History of edits (Latest: r3code 1 year, 2 months ago) §

Instead, I thought I’d try creating a single factory class, that uses Generics to allow you to change the key used to request an instance, and that uses Anonymous Methods to do the creating so as to avoid the necessity for mapping classes. Sticking with my report scenario above, here’s how I wanted to instantiate it:

Вместо этого, я подумал, попытаюсь создать один класс-фабрику с помощью универсальных шаблонов (дженериков), позволяющий менять ключ для запроса экземпляра. Класс, который использует анонимные методы, чтобы избежать необходимости использовать связующие классы для создания объектов. Опираясь на приведенный выше сценарий, вот как я хотел создавать экземпляр:

History of edits (Latest: r3code 1 year, 2 months ago) §

ReportFactory := TFactory<string , TBaseReport>.Create;

ReportFactory := TFactory<string , TBaseReport>.Create;

History of edits (Latest: r3code 2 years ago) §

Where the first generic parameter is the type of the key I will use to request a report, in this case a string representing the report name, and the second is the base type I want the Factory to return.

Где первый параметр универсального шаблона - это тип ключа используемого для запроса отчета (в данном случае строка прелстваляет имя отчета), второй параметр - это базовый тип, который фабрика будет мне возвращать.

History of edits (Latest: r3code 1 year, 3 months ago) §
Pages: ← previous Ctrl next next untranslated
1 2 3