I. Simple Factory Method

zhaozj2021-02-16  57

Abstract products: such as abstract fruits.

Specific product: Apple, grape, etc. inherited from Fruit.

Factory: Responsible for the production of various fruits.

Unit factoryMethodunit;

interfacetype TFruitID = (Grape, Apple); TFruit = class // abstract interface public constructor Create; virtual; end; TGrape = class (Fruit) // specific class constructor Create; override; end; TApple = class (Fruit) // specific Class constructor create; override;

Tcreator = Class // Factory Public Constructor Create; Virtual; Function CreateProduct (Fruitid: TFRuitid): TFRUIT; Virtual;

TMYCREATOR = Class (TCREATOR) Constructor Create; Override; Function CreateProduct (FRUTID: TFRUTID): TFRUIT; OVERRIDE; / / END;

IMPLEMentation

function TCreator.CreateProduct (FruitID: TFruitID): TFruit; var aProduct: TFruit; begin aProduct: = nil; if FruitID = Grape then aProduct: = TGrape.Create; if FruitID = Apple then aProduct: = TApple.Create; Result: = APROD;

Constructor tgrape.create; begin // ...... End;

Constructor Tapple.create; begin // ...... end;

Constructor tcreator.create; begin // ...... End;

Constructor TMYCREATOR.CREATE; Begin // ...

Function TMYCREATOR.CREATEPRODUCT (FRUTID: TFRUTID): TFRUIT; VAR APRODUCT: TFRUIT; Acreator: Tcreator; Begin

Aproduct: = nil; if fruitid = grape dam; = tgrape.create; if Fruitid = Apple Then Aproduct: = TAPPLE.CREATE

IF APRODUCT = NIL THEN BEGIN AcReator: = Tcreator.create; Aproduct: = Acreator.createProduct (Fruit); End; Result: = APRODUCT;

End.

转载请注明原文地址:https://www.9cbs.com/read-18902.html

New Post(0)