Главная страница
Top.Mail.Ru    Яндекс.Метрика
Текущий архив: 2006.07.23;
Скачать: CL | DM;

Вниз

Похожие компоненты   Найти похожие ветки 

 
DimaBr   (2005-12-27 09:27) [0]

Имеется несколько компонентов порожденных от разных предков к реализации которых добавлены идентичные методы с идентичной реализацией. Можно ли это упростить и как ?

TdiTimer = class(TTimer)
 private
   fOwner: TComponent;
   fCategory: string;
 protected
   procedure SetParentComponent(Value: TComponent); override;
 public
   function GetParentComponent: TComponent; override;
   constructor Create(AOwner: TComponent); override;
   destructor Destroy; override;
   function HasParent: Boolean; override;
   property Owner: TComponent read GetParentComponent write SetParentComponent;
 published
   property Category: string read fCategory write fCategory;
end;
TdiDataSource = class(TDataSource)
 private
   fOwner: TComponent;
   fCategory: string;
 protected
   procedure SetParentComponent(Value: TComponent); override;
 public
   function GetParentComponent: TComponent; override;
   constructor Create(AOwner: TComponent); override;
   destructor Destroy; override;
   function HasParent: Boolean; override;
   property Owner: TComponent read GetParentComponent write SetParentComponent;
 published
   property Category: string read fCategory write fCategory;
end;


 
Igorek ©   (2005-12-28 12:36) [1]

Можно. Интерфейсы + агрегация.


 
DimaBr   (2005-12-29 09:06) [2]

>Igorek ©
На сколько я понимаю Интерфейсы реализуют только шапку, а сама реализация возлагается на обекты. У меня же и шапка и реализация одинаковы. То есть идея породить компонент от двух, чего на сколько я понимаю в Delphi сделать нельзя.


 
Джо ©   (2005-12-29 16:38) [3]


> [2] DimaBr   (29.12.05 09:06)

Правильно сказал коллега [1] Igorek ©. Интерфейсы и аггрегация. Добавлю сюда делегацию. Как пример, схема такая:

type

 TBase1 = class
 end;

 TBase2 = class
 end;

 // интерфейс общих методов и свойств
 ICommonInterface = interface
   function GetCategory: string;
   procedure SetCategory (AValue: string);
   property Catagory: string read GetCategory write SetCategory;
 end;

 // класс реализует общие методы и свойства не напрямую,
 // а поручает (delegates) их другому классу, см. ниже в implementation
 TChildren1 = class (TBase1, ICommonInterface)
 private
   function GetCommonInterface: ICommonInterface;
 public
   property CommonInterface: ICommonInterface read GetCommonInterface
     implements ICommonInterface;
 end;

 // класс реализует общие методы и свойства не напрямую,
 // а поручает (delegates) их другому классу, см. ниже в implementation
 TChildren2 = class (TBase2, ICommonInterface)
 private
   function GetCommonInterface: ICommonInterface;
 public
   property CommonInterface: ICommonInterface read GetCommonInterface
     implements ICommonInterface;
 end;

implementation

type
 // класс реализует общие методы и свойства
 TCommonInterface = class (TInterfacedObject, ICommonInterface)
 private
   function GetCategory: string;
   procedure SetCategory (AValue: string);
 public
    // сюда будем передавать конкретный instance конкретного класса
   // возможно, это понадобится для разделения поведения в зависимости
   // от типа (class) объекта
   constructor Create (BaseObject: TObject);
 end;
....

function TChildren1.GetCommonInterface: ICommonInterface;
begin
 Result := TCommonInterface.Create (Self);
end;

...
function TChildren2.GetCommonInterface: ICommonInterface;
begin
 Result := TCommonInterface.Create (Self);
end;

....

В итоге:
1. вся общая функциональность вынесена в класс TCommonInterface.
2. к классам TChildren1 и TChildren2 можно напрямую обращаться как к имплементации общего интерфейса ICommonInterface.

В зависимости от всяких разных условий конкретная схема может варьироваться.

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


 
DimaBr   (2005-12-30 09:29) [4]


> Джо ©   (29.12.05 16:38) [3]

Спасибочки, если возможно то какую-нибудь толковую ссылочку про Агрегацию и Делегацию. Очень интересно !!!



Страницы: 1 вся ветка

Текущий архив: 2006.07.23;
Скачать: CL | DM;

Наверх




Память: 0.48 MB
Время: 0.031 c
2-1151929185
Id
2006-07-03 16:19
2006.07.23
Добавление полей в триггере


3-1148278150
petvv
2006-05-22 10:09
2006.07.23
Пустые поля после выполнения SQL запроса


2-1151852788
Gizza
2006-07-02 19:06
2006.07.23
Свернуть MainForm


2-1151918291
salexn
2006-07-03 13:18
2006.07.23
MessageBox и зависание программы


3-1148038085
DVM
2006-05-19 15:28
2006.07.23
Одна база Access - несколько клиентов