适配器模式——使得新环境中不需要去重复实现已经存在了的实现而很好地把现有对象(指原来环境中的现有对象)加入到新环境来使用。
适配器模式(Adapter Pattern)是作为两个不兼容的接口之间的桥梁。
这种类型的设计模式属于结构型模式,它结合了两个独立接口的功能。
这种模式涉及到一个单一的类,该类负责加入独立的或不兼容的接口功能。
举个真实的例子,读卡器是作为内存卡和笔记本之间的适配器。您将内存卡插入读卡器,
再将读卡器插入笔记本,这样就可以通过笔记本来读取内存卡。
该实例基于WPF实现,直接上代码,下面为三层架构的代码。
一 Model
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Interop;
namespace 设计模式练习.Model.适配器模式
{
//适配器类
internal class PowerAdapter : Tworole, Threehole
{
public string Msg { get; set; }
public void requset()
{
//在三孔插头的内部调用两孔插头的方法
string msg=string.Empty;
speciTwoRequest(ref msg);
Msg = msg;
}
}
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace 设计模式练习.Model.适配器模式
{
//三孔插头
public interface Threehole
{
public void requset();
}
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace 设计模式练习.Model.适配器模式
{
//两孔插头
public abstract class Tworole
{
public void speciTwoRequest(ref string msg)
{
msg = "两孔插头";
}
}
}
二 View
<Window x:Class="设计模式练习.View.适配器模式.Adapter"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:local="clr-namespace:设计模式练习.View.适配器模式"
mc:Ignorable="d"
Title="Adapter" Height="450" Width="800">
<Grid>
<Grid.ColumnDefinitions>
<ColumnDefinition/>
<ColumnDefinition/>
</Grid.ColumnDefinitions>
<Label Content="{Binding Res}" Grid.Column="0"/>
<Button Content="适配器" Grid.Column="1" Command="{Binding adapterCommand}"/>
</Grid>
</Window>
三 ViewModel
using CommunityToolkit.Mvvm.ComponentModel;
using CommunityToolkit.Mvvm.Input;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using 设计模式练习.Model.适配器模式;
namespace 设计模式练习.ViewModel.适配器模式
{
partial class Adapter_ViewModel : ObservableObject
{
[ObservableProperty]
private string res;
[RelayCommand]
private void adapter()
{
PowerAdapter powerAdapter = new PowerAdapter();
powerAdapter.requset();
Res = powerAdapter.Msg;
}
}
}