- Unit Classes;
- TBasicActionLink = class(TObject)
- private
- FOnChange: TNotifyEvent;
- protected
- FAction: TBasicAction;
- procedure AssignClient(AClient: TObject); virtual;
- procedure Change; virtual;
- function IsOnExecuteLinked: Boolean; virtual;
- procedure SetAction(Value: TBasicAction); virtual;
- procedure SetOnExecute(Value: TNotifyEvent); virtual;
- public
- constructor Create(AClient: TObject); virtual;
- destructor Destroy; override;
- function Execute(AComponent: TComponent = nil): Boolean; virtual;
- function Update: Boolean; virtual;
- property Action: TBasicAction read FAction write SetAction;
- property OnChange: TNotifyEvent read FOnChange write FOnChange;
- end;
- TBasicActionLinkClass = class of TBasicActionLink;
- { TBasicActionLink }
- constructor TBasicActionLink.Create(AClient: TObject);
- begin
- inherited Create;
- AssignClient(AClient);
- end;
- procedure TBasicActionLink.AssignClient(AClient: TObject);
- begin
- end;
- destructor TBasicActionLink.Destroy;
- begin
- if FAction <> nil then FAction.UnRegisterChanges(Self);
- inherited Destroy;
- end;
- procedure TBasicActionLink.Change;
- begin
- if Assigned(OnChange) then OnChange(FAction);
- end;
- function TBasicActionLink.Execute(AComponent: TComponent): Boolean;
- begin
- FAction.ActionComponent := AComponent;
- Result := FAction.Execute;
- end;
- procedure TBasicActionLink.SetAction(Value: TBasicAction);
- begin
- if Value <> FAction then
- begin
- if FAction <> nil then FAction.UnRegisterChanges(Self);
- FAction := Value;
- if Value <> nil then Value.RegisterChanges(Self);
- end;
- end;
- function TBasicActionLink.IsOnExecuteLinked: Boolean;
- begin
- Result := True;
- end;
- procedure TBasicActionLink.SetOnExecute(Value: TNotifyEvent);
- begin
- end;
- function TBasicActionLink.Update: Boolean;
- begin
- Result := FAction.Update;
- end;
- 在上面的代码中我们可以看到TBasicActionLink的Execute方法实际上也就是调用了TBasicAction对象的虚方法Execute来负责响应客户端的请求。
-
应用举例
-
在通常的UI设计中,我们会在Form上放置一些菜单项,同时会把部分使用频率较高的功能以工具栏形式提供给用户。这些工具栏按钮实现的功能与菜单项完全相同,我们就可以使用Action模式来设计这些请求,然后将菜单项和工具栏按钮与这些Action对象对立关联即可。即使以后在用户界面上增加其它形式的调用,如上下文菜单,或是快捷键等,都可以直接与这些请求对象建立关联。可以很轻松地扩充用户发出请求的方式。
-