MyBean简单入门学习(2)

dll改造
1.新建一个Dynamic Library项目
2.添加一个VCL Form
3.将EXE中创建的接口单元引入
4.在窗体内中将加入接口单元内的两个接口

//原代码
type
  TfrmPlug1 = class(TForm)
    Memo1: TMemo;
    Button1: TButton;
    Label1: TLabel;
    Button2: TButton;
    Edit1: TEdit;
    Memo2: TMemo;
    procedure FormCreate(Sender: TObject);
    procedure Button1Click(Sender: TObject);
    procedure Button2Click(Sender: TObject);
  private
//修改为
type
  TfrmPlug1 = class(TForm,IShowForm,IMainPlugCom)
    Memo1: TMemo;
    Button1: TButton;
    Label1: TLabel;
    Button2: TButton;
    Edit1: TEdit;
    Memo2: TMemo;
    procedure FormCreate(Sender: TObject);
    procedure Button1Click(Sender: TObject);
    procedure Button2Click(Sender: TObject);
  private

5.在public中实现接口中接口的功能。

//public中定义这些代码
  public
    procedure ShowAsNoraml;stdcall;
    procedure ShowAsMdi;stdcall;
    procedure Receive(msg:PChar);stdcall;
    procedure Send(msg:PChar);stdcall;
    procedure addtomemo(str:string);
    { Public declarations }
  end;

需实现的代码参考如下:

procedure TfrmPlug1.Send(msg: PChar);
var
  com:IMainPlugCom;
begin
//获取exe程序中IMainPlugCom接口
  com := TMyBeanFactoryTools.GetObject('main') as IMainPlugCom;
//判断是否获取成功
  if com<>nil then
  begin
//操作exe中的Recvive方法
    com.Receive(msg);
  end;
//获取plug2.dll中IMainPlugCom接口
  com := TMyBeanFactoryTools.GetObject('plug2') as IMainPlugCom;
//判断是否获取成功
  if com<>nil then
  begin
//操作dll中的Recvive方法
    com.Receive(msg);
  end;
end;

//定义自身中Receive方法
procedure TfrmPlug1.Receive(msg: PChar);
var
  str :string;
begin
  str :=string(msg);
  addtomemo('接受到的消息:'+str);//单例模式可以直接显示
 Show;
end;

6.在该dll的dpr文件的begin .. end.中添加注册函数

//第一个参数为注册名,第二个为需要创建的实例,第三个参数表示是否是单实例创建(按照天地玄的视频说法,该参数提供了dll是否在运行过程中达到解耦的目的,如果为True,在运行过程中,无论多少个不同dll调用该实例,该实例只创建一次,如果设置为False则每次调用都创建一个实例。)
beanFactory.RegisterBean('plug1', TfrmPlug1,True)

7.最后需要在该dll的dpr文件中uses下引用mybean.core.beanFactory单元

uses mybean.core.beanFactory;

你可能感兴趣的:(MyBean简单入门学习(2))