目录
NewObject()是最简单的工厂模式,他需要可选的外部对象和类,并会创建拥有自动生成的名称 的新实例。
抽象类
- // 抽象类
- UCLASS(Abstract)
- class DESIGNPATTERNS_API UProductObject : public UObject
- {
- GENERATED_BODY()
- public:
- virtual void ShowInfo() { check(0 && "You must override this"); }
- };
产品(具体类)
- // 具体类A
- UCLASS()
- class DESIGNPATTERNS_API UProductA : public UProductObject
- {
- GENERATED_BODY()
- public:
- virtual void ShowInfo() override {
- UE_LOG(LogTemp, Warning, TEXT(__FUNCTION__" This is a ProductA"));
- }
- };
-
- // 具体类B
- UCLASS()
- class DESIGNPATTERNS_API UProductB : public UProductObject
- {
- GENERATED_BODY()
- public:
- virtual void ShowInfo() override {
- UE_LOG(LogTemp, Warning, TEXT(__FUNCTION__" This is a ProductB"));
- }
- };
工厂类
- // 工厂类
- UCLASS()
- class DESIGNPATTERNS_API UFactoryObject : public UObject
- {
- GENERATED_BODY()
- public:
-
- static UProductObject* CreateNewProduct(UObject* Outer,TSubclassOf
ProductClass) { - // 此处注意 TSubclassOf 和 NewObject的结合用法
- return NewObject
(Outer, ProductClass); - }
- };
测试:
- // 调用测试用的Actor
- UCLASS()
- class DESIGNPATTERNS_API AFactoryActor : public AActor
- {
- GENERATED_BODY()
- public:
-
- void BeginPlay() override {
- UProductObject* ProductA = UFactoryObject::CreateNewProduct(this,UProductA::StaticClass());
- ProductA->ShowInfo();
-
- UProductObject* ProductB = UFactoryObject::CreateNewProduct(this,UProductB::StaticClass());
- ProductB->ShowInfo();
- }
- };
- LogTemp: Warning: UProductA::ShowInfo This is a ProductA
- LogTemp: Warning: UProductB::ShowInfo This is a ProductB