Prototype是如何应用的?(50分)

  • 主题发起人 主题发起人 Gooder
  • 开始时间 开始时间
G

Gooder

Unregistered / Unconfirmed
GUEST, unregistred user!
本人看了设计模式后,对prototype原型模式不太懂行,不知道它的结构是如何
它是如何应用的?能具个列子给我吗?
 
unit Unit1;
interface
uses
Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs,
StdCtrls;
type
ShapeList = class(TList)
public
procedure Draw;
end;

Shape = class(TObject)
private
Lx, Ly: Integer;
public
constructor Create;
procedure SetXY(X, Y: Integer);
procedure Draw;
virtual;
abstract;
function Clone: Shape;
virtual;
abstract;
end;

Circle = class(Shape)
procedure Draw;
override;
function Clone: Shape;
override;
end;

Rect = class(Shape)
procedure Draw;
override;
function Clone: Shape;
override;
end;

TForm1 = class(TForm)
Button1: TButton;
Button2: TButton;
Button3: TButton;
procedure Button1Click(Sender: TObject);
procedure FormCreate(Sender: TObject);
procedure Button2Click(Sender: TObject);
private
{ Private declarations }
public
{ Public declarations }
end;

var
Form1 : TForm1;
List : ShapeList;
PShape: Shape;
implementation
{$R *.DFM}
procedure TForm1.Button1Click(Sender: TObject);
var
Ps: Shape;
begin
with Canvasdo
begin
PShape := List.Get(0);
ps := PShape.Clone;
List.Add(ps);
List.Draw;
end;
end;

procedure TForm1.FormCreate(Sender: TObject);
begin
List := ShapeList.Create;
PShape := Circle.Create;
PShape.SetXY(10, 10);
List.Add(PShape);
PShape := Rect.Create;
PShape.SetXY(50, 50);
List.Add(PShape);
end;

{ ShapeList }
procedure ShapeList.Draw;
var
i: Integer;
begin
for i := 0 to Self.Count-1do
begin
PShape := Self.Get(i);
PShape.Draw;
end;
end;

{ Shape }
constructor Shape.Create;
begin
Lx := 80;
Ly := 80;
end;

procedure Shape.SetXY(X, Y: Integer);
begin
Lx := X;
Ly := Y;
end;

{ Circle }
function Circle.Clone: Shape;
begin
Result := Circle.Create;
end;

procedure Circle.Draw;
begin
with Form1.Canvasdo
begin
pen.Color := clRed;
pen.Width := 1;
Ellipse(Lx, Ly, 130, 130);
end;

end;

{ Rect }
function Rect.Clone: Shape;
begin
Result := Rect.Create;
end;

procedure Rect.Draw;
begin
with Form1.Canvasdo
begin
pen.Color := clRed;
pen.Width := 1;
Rectangle(Lx, Ly, 110, 150);
end;
end;

procedure TForm1.Button2Click(Sender: TObject);
begin
with Canvasdo
begin
PShape := List.Get(TButton(Sender).Tag);
PShape.Draw;
end;
end;

end.
 
反对就模式谈模式!
模式是用来解决问题的,因而在讨论用哪种模式之前必须首先明确问题。
 
模式是在特定条件下解决特定问题的一般方法,具体实现因为条件不同,可能实现也不太一样。
希望能共同学习,有所收获
 
后退
顶部