009.Delphi插件之QPlugins,服务的热插拔

这个DEMO用来演示服务的替换,用起来总是怪怪的感觉,效果图如下

009.Delphi插件之QPlugins,服务的热插拔_第1张图片

代码如下

unit Frm_Main;

interface

uses
  Winapi.Windows,
  Winapi.Messages,
  System.SysUtils,
  System.Variants,
  System.Classes,
  Vcl.Graphics,
  Vcl.Controls,
  Vcl.Forms,
  Vcl.Dialogs,
  Vcl.ExtCtrls,
  Vcl.StdCtrls,
  qplugins_base,
  QPlugins;

type
  // 定义一个接口,方法由子类来实现
  IEchoService = interface
    ['{E9A9E0D8-F278-46CC-9AA4-7FCD9CDAB77F}']
    function Echo(S: string): string;
  end;

  // Echo接口的实例
  TEchoService = class(TQService, IEchoService)
    function Echo(S: string): string;
  end;

  TEchoReplacement = class(TInterfacedObject, IEchoService)
    function Echo(S: string): string;
  end;

  TForm_Main = class(TForm)
    Button1: TButton;
    Memo1: TMemo;
    Panel1: TPanel;
    Button2: TButton;
    procedure Button1Click(Sender: TObject);
    procedure FormCreate(Sender: TObject);
    procedure Button2Click(Sender: TObject);
  private
    { Private declarations }
    FReplaced: IEchoService;
  public
    { Public declarations }
  end;

var
  Form_Main: TForm_Main;

implementation

{$R *.dfm}

// 按钮_调用服务
procedure TForm_Main.Button1Click(Sender: TObject);
var
  AService: IEchoService;
begin
  // PluginsManager函数返回全局PluginsManager实例
  AService := PluginsManager as IEchoService;
  // 服务存在,则调用
  if Assigned(AService) then
  begin
    Memo1.Lines.Add(AService.Echo('服务插件'));
  end;
end;

// 按钮_替换服务
procedure TForm_Main.Button2Click(Sender: TObject);
var
  AService: IQService;
begin
  // 在指定的父结点下,查找指定路径的服务
  AService := FindService('/Services/Echo');
  // 如果服务存在
  if Assigned(AService) then
  begin
    // 撤销替换服务
    if Assigned(FReplaced) then
    begin
      AService.RemoveExtension(FReplaced);
      FReplaced := nil;
      Button2.Caption := '替换服务';
    end
    else
    begin
      // 替换服务
      FReplaced := TEchoReplacement.Create;
      AService.AddExtension(FReplaced);
      Button2.Caption := '撤销替换';
    end;
  end;
end;
{ TEchoService }

// 原Echo函数
function TEchoService.Echo(S: string): string;
begin
  Result := Format('类名[%s]: %s', [ClassName, S]);
end;

{ TEchoReplacement }
// 新Echo函数
function TEchoReplacement.Echo(S: string): string;
begin
  Result := Format('新类名[%s]: %s', [ClassName, S]);
end;

// 创建
procedure TForm_Main.FormCreate(Sender: TObject);
begin
  // 注册TEchoService服务
  RegisterServices('/Services', [TEchoService.Create(IEchoService, 'Echo')]);
end;

end.

 

转载于:https://www.cnblogs.com/tianpan2019/p/11496687.html

你可能感兴趣的:(009.Delphi插件之QPlugins,服务的热插拔)