将一个接口转换成客户希望的另一个接口,适配器模式使接口不兼容的那些类可以一起工作,其别名为包装器(Wrapper)。
假设自定义一个媒体播放器,接口已经写好,为了使第三方SDK适应自己的接口,此时可以使用适配器。
创建目标抽象类,此处以接口形式
UINTERFACE(MinimalAPI)
class UMediaInterface : public UInterface
{
GENERATED_BODY()
};
class DESIGNPATTERNS_API IMediaInterface
{
GENERATED_BODY()
public:
virtual void PlayVideo(const FString& Filepath) = 0;
};
创建目适配者类 —— Uffmpeg 、UVLC
UCLASS() // 适配者类 —— ffmpeg
class DESIGNPATTERNS_API Uffmpeg : public UObject
{
GENERATED_BODY()
public:
virtual void OpenFile(const FString& Filepath) {
UE_LOG(LogTemp, Warning, TEXT(__FUNCTION__" use ffmpeg sdk to play media"));
}
};
UCLASS() // 适配者类 —— VLC
class DESIGNPATTERNS_API UVLC : public UObject
{
GENERATED_BODY()
public:
virtual void OpenFile(const FString& Filepath) {
UE_LOG(LogTemp, Warning, TEXT(__FUNCTION__" use VLC sdk to play media"));
}
};
创建适配器类,继承自目标抽象类 —— UffmpegAdapter、UffmpegAdapter
UCLASS() // 适配器类 —— UffmpegAdapter
class DESIGNPATTERNS_API UffmpegAdapter : public UObject, public IMediaInterface
{
GENERATED_BODY()
public:
UPROPERTY()
Uffmpeg* m_pffmpegSDK;
UffmpegAdapter() {
m_pffmpegSDK=NewObject<Uffmpeg>();
}
~UffmpegAdapter() {}
virtual void PlayVideo(const FString& Filepath) override {
m_pffmpegSDK->OpenFile(Filepath);
}
};
UCLASS() // 适配器类 —— UVLCAdapter
class DESIGNPATTERNS_API UffmpegAdapter: public UObject, public IMediaInterface
{
GENERATED_BODY()
public:
UPROPERTY()
UVLC* m_pVLCSDK;
UVLCAdapter() {
m_pVLCSDK = NewObject<UVLC>();
}
~UVLCAdapter() {}
virtual void PlayVideo(const FString& Filepath) override {
m_pVLCSDK->OpenFile(Filepath);
}
};
调用测试
UCLASS()
class DESIGNPATTERNS_API AAdapterTestActor : public AActor
{
GENERATED_BODY()
public:
AAdapterTestActor();
protected:
// Called when the game starts or when spawned
virtual void BeginPlay() override {
// 使用 ffmpegAdapter 适配器
IMediaInterface* MediaPlayer = Cast<IMediaInterface>(NewObject<UffmpegAdapter>());
MediaPlayer->PlayVideo(TEXT("C:/浪客剑心.最终章.人诛篇.mp4"));
// 使用 VLCAdapter 适配器
MediaPlayer = Cast<IMediaInterface>(NewObject<UVLCAdapter>());
MediaPlayer->PlayVideo(TEXT("C:/浪客剑心.最终章.人诛篇.mp4"));
}
};
调式输出
LogTemp: Warning: Uffmpeg::OpenFile use ffmpeg sdk to play media
LogTemp: Warning: UVLC::OpenFile use VLC sdk to play media
【UE4 设计模式】适配器模式 Adapter Pattern
原文:https://www.cnblogs.com/shiroe/p/14908316.html