原型模式表示克隆现有对象而不是创建新对象,也可以根据需要进行定制。
如果创建新对象的成本昂贵且资源密集,则应遵循此模式。
原型模式的优势
原型模式的主要优点如下:
- 它减少了子分类的需要。
- 它隐藏了创建对象的复杂性。
- 客户端可以在不知道它将是哪种类型的对象的情况下获取新对象。
- 它允许您在运行时添加或删除对象。
原型模式的使用
- 在运行时实例化类时。
- 当创建对象的成本昂贵或复杂时。
- 当您希望将应用程序中的类数保持最少时。
- 当客户端应用程序需要不知道对象的创建和表示时。
原型模式的 UML
unit PrototypePatternImpl;
interface
uses System.SysUtils;
type
IPrototype = interface
['{1E61DB8E-ECC9-45C2-8D3D-2B064A1CF1D8}']
function getClone: IPrototype ;
end;
TEmployeeRecord = class(TInterfacedObject, IPrototype)
private
Fid: integer;
Fname, Fdesignation, Faddress: String;
Fsalary: Extended;
public
constructor create; overload;
constructor create( Aid : integer; Aname, Adesignation : String; Asalary : Extended; Aaddress : String);overload;
function getClone: IPrototype ;
procedure showRecord;
end;
implementation
procedure TEmployeeRecord.showRecord;
begin
Writeln(Fid.ToString + #9 + Fname + #9 + Fdesignation+ #9 + Fsalary.ToString + #9 + Faddress);
end;
constructor TEmployeeRecord.create;
begin
System.Writeln(' Employee Records of Oracle Corporation ');
System.Writeln('---------------------------------------------');
System.Writeln('Eid'#9 +'Ename'#9 + 'Edesignation'#9 +'Esalary'#9#9+'Eaddress');
end;
constructor TEmployeeRecord.Create( Aid : integer; Aname, Adesignation : String; Asalary : Extended; Aaddress : String);
begin
Create;
self.Fid := Aid;
self.Fname := Aname;
self.Fdesignation := Adesignation;
self.Fsalary := Asalary;
self.Faddress := Aaddress;
end;
function TEmployeeRecord.getClone: IPrototype ;
begin
Result := TEmployeeRecord.Create(Fid,Fname,Fdesignation,Fsalary,Faddress);
end;
end.