代理模式

为其他对象提供一种代理以控制对这个对象的访问

1、远程代理:在.net中,引用外部的WebService就是一种代理模式。

2、虚拟代理:根据需要,创建开销很大的对象。通过它来存放,需要很长事件实例化的真实对象。

3、安全代理:控制真实对象访问时的权限。

4、只能引用:调用真实对象的时候,代理处理另外一些事。

 

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Proxy
{
    class SchoolGirl
    {
        private string name;

        public string Name
        {
            get { return name; }
            set { name = value; }
        }

    }
}
实体类

 

 

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Proxy
{
    interface IGiveGift//代理接口
    {
        void GiveDolls();
        void GiveFlower();
        void GiverChocolate();
    }
}
代理接口(IGiveGift)

 

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Proxy
{
    class Pursuit : IGiveGift//唯一变化就是让“追求者” 去实现“送礼物” 接口
    {
        SchoolGirl mm;
        public Pursuit(SchoolGirl mm)
        {
            this.mm = mm;
        }
        public void GiveDolls()
        {
            Console.WriteLine(mm.Name + "送你洋娃娃!");
        }
        public void GiveFlowers()
        {
            Console.WriteLine(mm.Name + "送你鲜花!");
        }
        public void GiveChocolate()
        {
            Console.WriteLine(mm.Name + "送你巧克力!");
        }
    }
}
接口中的具体实现(Pursuit)
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Proxy
{
    class Proxy:IGiveGift//proxy 类保存一个引用,使得代理可以访问实体,并提供一个与subject的接口相同的接口,这样代理就可以用来替代实体
    {
        Pursuit gg;
        public Proxy(SchoolGirl mm) {
            gg = new Pursuit(mm);
        }
        public void GiveDolls() {
            gg.GiveDolls();
        }
        public void GiveChocolate()
        {
            gg.GiveChocolate();
        }
        public void GiveFlowers()
        {
            gg.GiveFlowers();
        }
    }
}
Proxy类
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Proxy
{
    class Program
    {
        static void Main(string[] args)
        {
            SchoolGirl jiaojiao = new SchoolGirl();
            jiaojiao.Name = "娇娇";
            //这里创建了proxy对象,但是,这个对象最终运行的代码,都是在Pursuit类中具体实现的。
            Proxy daili = new Proxy(jiaojiao);
            daili.GiveChocolate();
            daili.GiveDolls();
            daili.GiveFlowers();
        }
    }
}
主程序

 

转载于:https://www.cnblogs.com/vichin/p/8419682.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值