【设计模式】结构型模式

结构型模式:

1.适配器模式:

定义: 通过一个类的接口转换成客户希望的另外一个接口,使原本由于接口不兼容而不能在一起工作的那些类可以一起工作

分类:适配器从结构上分为: 类适配器和对象适配器,其中类适配器使用继承关系,对象适配器使用对象引用 来进行适配

举例:以手机充电器为例

对象适配器:

//目标类: 
//客户所期待的接口。目标可以是具体的或抽象的类,也可以是接口。
Public class Target
{
	Public virtual void TargetPrint()
	{
		Console.WriteLine("my name is Target!")
	}
}


//需要适配的类:
Public class Adaptee
{
	Public void AdapteePrint()
	{
		Console.WriteLine("my name is Adaptee")
	}
}

//适配器类: 
Public class Adapter : Target
{
	Private Adaptee adaptee =new Adaptee();  //实例化需要适配的类
	Public override void TargetPrint()
	{
		Adaptee.AdapteePrint();调用需要适配的方法
	}
}

最终结果:

我个人感觉适配器最关键的部分就是适配器类:

如下:

 

如下是我大概画的结构图:

2.桥接模式:

桥接模式的用意是将抽象化与实现化脱藕,使得二者可以独立的变化

耦合是指俩个对象的行为的某种强关联,脱藕则是要去掉他们之间的强关联,

在这里脱藕是指将抽象化和实现化之间的耦合解脱,或者将他们之间的强关联换成弱关联,将俩者之间的继承关系改为聚合关系,就是将他们之间的强关联改换为弱关联。

 

桥接模式中的脱耦,是指抽象化和实现化之间使用组合/聚合关系,而不是继承关系,从而使两者可以相对独立地变化

1.抽象化对象

/// <summary>
    /// 抽象概念中的充电器,扮演抽象化角色
    /// </summary>
    public class Charger
    {
        // 字段
        private Phone implementor;
// 属性
        public Phone Implementor
        {
            get { return implementor; }
            set { implementor = value; }
        }
/// <summary>
        /// 电压,这里抽象类中不再提供实现了,而是调用实现类中的实现
        /// </summary>
        public virtual void Voltage()
        {
            implementor.Voltage();
        }
/// <summary>
        /// 接口形状
        /// </summary>
        public virtual void Shape()
        {
            implementor.Shape();
        }
    }

2.改善后的抽象化对象:

// <summary>
    /// 具体充电器
    /// </summary>
    public class ConcreteCharger : Charger
    {
        public override void Voltage()
        {
            Console.WriteLine("---------------------");
            base.Voltage();
        }
    }

 

 

3.实现者角色和具体实现者角色

3.实现者角色
/// <summary>
    /// 手机,提供抽象方法
    /// </summary>
    public abstract class Phone
    {
        public abstract void Voltage();
        public abstract void Shape();
    }
//4.具体实现者角色

 // <summary>
    /// 小米手机,重写基类的抽象方法
    /// 提供具体的实现
    /// </summary>
    public class XiaoMi : Phone
    {
        public override void Voltage()
        {
            Console.WriteLine("小米牌手机充电器电压");
        }
public override void Shape()
        {
            Console.WriteLine("小米牌手机充电器接口形状");
        }
    }
/// <summary>
    /// 华为手机,重写基类的抽象方法
    /// </summary>
    public class HuaWei :Phone
    {
        public override void Voltage()
        {
            Console.WriteLine("华为牌手机充电器电压");
        }
public override void Shape()
        {
            Console.WriteLine("华为牌手机充电器接口形状");
        }
    }

4.使用桥接模式

/// <summary>
    /// 以电视机遥控器的例子来演示桥接模式
    /// </summary>
    class Client
    {
        static void Main(string[] args)
        {
            // 创建一个充电器
            Charger charger = new Charger();
            // 小米手机
            charger .Implementor = new XiaoMi();
            charger .Voltage();
            charger .Shape();
            Console.WriteLine();
// 华为手机
            charger .Implementor = new HuaWei();
            charger .Voltage();
            charger .Shape();
            Console.Read();
        }
    }

在上面这个例子中,充电器的功能实现方法不再是充电器抽象类中去实现,而是把实现部分用另一个手机类去封装,

然后充电器中只包含手机类的一个引用。

下面是我根据这个例子画的结构图:

3.装饰模式:

 动态地给一个对象添加一些额外的职责,就增加功能来说,装饰模式比生成子类更为灵活

 装饰模式是一种用于替代继承的技术,它通过一种无须定义子类的方式来给对象动态增加职责,使用对象之间的关联关系取代类   之间的继承关系

 

4.组合模式:

将对象组合成树形结构以表示“部分--整体”的层次结构,组合模式使得用户对单个对象和组合对象的使用具有一致性

//Leaf: 在组合中表示叶节点对象,叶节点没有子节点
//Composite:定义有枝节点行为,用来存储子部件

public abstract class Component
    {
        protected string _name;
public Component(string name)
        {
            this._name = name;
        }
public abstract void Add(Component c);
public abstract void Remove(Component c);
public abstract void Display(int depth);
    }
public class Leaf : Component
    {
        public Leaf(string name)
            : base(name)
        {
        }
public override void Add(Component c)
        {
            Console.WriteLine("Cannot add to a leaf");
        }
public override void Remove(Component c)
        {
            Console.WriteLine("Cannot remove from a leaf");
        }
public override void Display(int depth)
        {
            Console.WriteLine(new String('-', depth) + _name);
        }
    }
public class Composite : Component
    {
        private List<Component> _children = new List<Component>();
public Composite(string name)
            : base(name)
        {
        }
public override void Add(Component component)
        {
            _children.Add(component);
        }
public override void Remove(Component component)
        {
            _children.Remove(component);
        }
public override void Display(int depth)
        {
            Console.WriteLine(new String('-', depth) + _name);
foreach (Component component in _children)
            {
                component.Display(depth + 2);
            }
        }
    }
 public class Client
    {
        static void Main(string[] args)
        {
            // 生成树根root,根上长出俩叶LeafA和LeafB
            Composite root = new Composite("root");
            root.Add(new Leaf("Leaf A"));
            root.Add(new Leaf("Leaf B"));
//根上长出分枝Composite X,分枝上也有俩叶Leafxa和Leafxb
Composite comp = new Composite("Composite X");
            comp.Add(new Leaf("Leaf XA"));
            comp.Add(new Leaf("Leaf XB"));
root.Add(comp);
            root.Add(new Leaf("Leaf C"));
// Add and remove a leaf
            Leaf leaf = new Leaf("Leaf D");
            root.Add(leaf);
            root.Remove(leaf);
// Recursively display tree
            root.Display(1);
        }
    }
-root
---Leaf A
---Leaf B
---Composite X
-----Leaf XA
-----Leaf XB
---Leaf C

5.外观模式: 

为子系统中的一组接口提供一个一致的界面,此模式定义了一个高层接口,

每一个子系统不是一个独立的类,而是一个类的集合

下面是一个例子:这是一个在网上银行消费的过程

class Program
    {
        static void Main(string[] args)
        {
            SystemFAcade facade = new SystemFAcade();
            facade.Buy();
            Console.Read();

        }
    }



//身份认证子系统A
    public class AuthoriationSystemA
    {
        public void MethodA()
        {
            Console.WriteLine("执行身份认证");
        }
    }
    //系统安全子系统B
    public class SecurityStstemB
    {
        public void MethodB()
        {
            Console.WriteLine("执行系统安全检查");

        }
    }
    //网银安全子系统C
    public class NetBankSystemc
   
    {
        public void MethodC()
        {
            Console.WriteLine("执行网银安全监测");
        }
    }


//更高层的Facade
    public class SystemFAcade
    {
        AuthoriationSystemA auth;
        SecurityStstemB security;
        NetBankSystemc netbank;
        public SystemFAcade()
        {
            auth = new AuthoriationSystemA();
            security = new SecurityStstemB();
            netbank = new NetBankSystemc();

        }
        public void Buy()
        {
            auth.MethodA(); //身份认证子系统
            security.MethodB();//系统安全子系统
            netbank.MethodC();//网银安全子系统

            Console.WriteLine("我已经成功购买了");

        }
    }

6.享元模式:

运动共享技术有效地支持大量细粒度的对象,它使用共享物件,用来尽可能减少内存使用量

 

7.代理模式:

 

在软件开发过程中,有些对象有时候会由于网络或其他的障碍,以至于不能够或者直接访问这些对象,如果直接访问会给系统带来不必要的复杂,所以增加一个代理对象代替目标对象,然后客户端只需要访问代理对象,由代理对象去帮我们去请求目标并返回结果给客户端

 

 

在现实生活中,如果有同事出国或者朋友出国的情况下,我们经常会拖这位朋友帮忙带一些电子产品或化妆品等东西,这个场景中,出国的朋友就是一个代理,他(她)是他(她)朋友的一个代理,由于他朋友不能去国外买东西,他却可以,所以朋友们都托他帮忙带一些东西的。下面就以这个场景来实现下代理模式,具体代码如下:

// 客户端调用
    class Client
    {
        static void Main(string[] args)
        {
            // 创建一个代理对象并发出请求
            Person proxy = new Friend();
            proxy.BuyProduct();
            Console.Read();
        }
    }

    // 抽象主题角色
    public abstract class Person
    {
        public abstract void BuyProduct();
    }

    //真实主题角色
    public class RealBuyPerson : Person
    {
        public override void BuyProduct()
        {
            Console.WriteLine("帮我买一个IPhone和一台苹果电脑");
        }
    }

    // 代理角色
    public class Friend:Person
    {
        // 引用真实主题实例
        RealBuyPerson realSubject;

        public override void BuyProduct()
        {
            Console.WriteLine("通过代理类访问真实实体对象的方法");
            if (realSubject == null)
            {
                realSubject = new RealBuyPerson();
            }

            this.PreBuyProduct();
            // 调用真实主题方法
            realSubject.BuyProduct();
            this.PostBuyProduct();
        }

        // 代理角色执行的一些操作
        public void PreBuyProduct()
        {
            // 可能不知一个朋友叫这位朋友带东西,首先这位出国的朋友要对每一位朋友要带的东西列一个清单等
            Console.WriteLine("我怕弄糊涂了,需要列一张清单,张三:要带相机,李四:要带Iphone...........");
        }
        
        // 买完东西之后,代理角色需要针对每位朋友需要的对买来的东西进行分类
        public void PostBuyProduct()
        {
            Console.WriteLine("终于买完了,现在要对东西分一下,相机是张三的;Iphone是李四的..........");
        }
    }

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 11
    评论
以下是几种常见的Java结构设计模式: 1. 适配器模式(Adapter Pattern):适配器模式用于将一个类的接口转换成客户端所期望的另一个接口。它允许不兼容的类能够合作。例如,将一个已有的类的接口转换成另一个接口,以满足客户端的需求。 ```java public interface MediaPlayer { public void play(String audioType, String fileName); } public interface AdvancedMediaPlayer { public void playVlc(String fileName); public void playMp4(String fileName); } public class VlcPlayer implements AdvancedMediaPlayer { public void playVlc(String fileName) { System.out.println("Playing vlc file. Name: " + fileName); } public void playMp4(String fileName) { // do nothing } } public class Mp4Player implements AdvancedMediaPlayer { public void playVlc(String fileName) { // do nothing } public void playMp4(String fileName) { System.out.println("Playing mp4 file. Name: " + fileName); } } public class MediaAdapter implements MediaPlayer { AdvancedMediaPlayer advancedMusicPlayer; public MediaAdapter(String audioType) { if (audioType.equalsIgnoreCase("vlc")) { advancedMusicPlayer = new VlcPlayer(); } else if (audioType.equalsIgnoreCase("mp4")) { advancedMusicPlayer = new Mp4Player(); } } public void play(String audioType, String fileName) { if (audioType.equalsIgnoreCase("vlc")) { advancedMusicPlayer.playVlc(fileName); } else if (audioType.equalsIgnoreCase("mp4")) { advancedMusicPlayer.playMp4(fileName); } } } public class AudioPlayer implements MediaPlayer { MediaAdapter mediaAdapter; public void play(String audioType, String fileName) { if (audioType.equalsIgnoreCase("mp3")) { System.out.println("Playing mp3 file. Name: " + fileName); } else if (audioType.equalsIgnoreCase("vlc") || audioType.equalsIgnoreCase("mp4")) { mediaAdapter = new MediaAdapter(audioType); mediaAdapter.play(audioType, fileName); } else { System.out.println("Invalid media. " + audioType + " format not supported"); } } } public class Main { public static void main(String[] args) { AudioPlayer audioPlayer = new AudioPlayer(); audioPlayer.play("mp3", "beyond the horizon.mp3"); audioPlayer.play("mp4", "alone.mp4"); audioPlayer.play("vlc", "far far away.vlc"); audioPlayer.play("avi", "mind me.avi"); } } ```

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 11
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值