C#深度学习の接口传参(interface)-----接口的妙用
2021-07-01 01:10
标签:factor spl 常用 ++ 封装 null hide cto 不同 一、接口可以干嘛 我们知道,接口的本质是一个约束规范,委托是方法纵向(形式上)的封装,接口是不同方法横向(广度)的封装 接口中不能有变量,但是可以有属性方法。常见的,我们可以用接口: 1、实现需求方的方法 2、接口作为参数,实现对不同类的解耦,下面是常见的男女类 3、接口作返回值,返回一个实现了接口的对象,基本和上面的例子类似 二、接口可以传参(常用来做对外SDK) 下面以两种常见构型讲解 1、A工厂生产产品,B工厂代理,C工厂卖,于是我们: 调用 2、工厂A生产,D直接代理 调用: 学习请加qq群:568055323 C#深度学习の接口传参(interface)-----接口的妙用 标签:factor spl 常用 ++ 封装 null hide cto 不同 原文地址:https://www.cnblogs.com/xietianjiao/p/9964789.html public interface ISay
{
void Say();
}
public class Man:ISay
{
public void Say()
{
Console.WriteLine("你好,我是男士!");
}
}
public class Woman : ISay
{
public void Say()
{
Console.WriteLine("你好,我是女士!");
}
}
public class Peole
{
public void Say(ISay iPeople)
{
iPeople.Say();
}
}
class Program
{
static void Main(string[] args)
{
Man man = new Man();
Woman woman = new Woman();
Peole peole = new Peole();
peole.Say(man);
peole.Say(woman);
Console.ReadLine();
}
}
public interface ITransfer
{
void Transfer(string msg);
}
public class FactoryA
{
public ITransfer FacATransfer = null;
public FactoryA()
{
product();
}
public void product()
{
int produceNum=0;
Task.Factory.StartNew(()=>
{
while (true)
{
produceNum++;
FacATransfer?.Transfer(String.Format("来自FactoryA的第{0}个产品", produceNum));
Thread.Sleep(2000);
}
});
}
}
public class FactoryB //中间商
{
public void ConnectInit(ITransfer transfer)
{
FactoryA factoryA = new FactoryA();
factoryA.FacATransfer = transfer;
}
}
public class FactoryC:ITransfer
{
public FactoryC()
{
FactoryB factoryB = new FactoryB();
factoryB.ConnectInit(this);
}
public void Transfer(string msg)
{
Console.WriteLine("为FactoryC生产,"+msg);
}
}
class Program
{
static void Main(string[] args)
{
FactoryC factoryC = new FactoryC();
//FactoryD factoryD = new FactoryD();
Console.ReadLine();
}
}
public class FactoryA
{
public ITransfer FacATransfer = null;
public FactoryA()
{
product();
}
public void product()
{
int produceNum=0;
Task.Factory.StartNew(()=>
{
while (true)
{
produceNum++;
FacATransfer?.Transfer(String.Format("来自FactoryA的第{0}个产品", produceNum));
Thread.Sleep(2000);
}
});
}
}
class Program
{
static void Main(string[] args)
{
//FactoryC factoryC = new FactoryC();
FactoryD factoryD = new FactoryD();
Console.ReadLine();
}
}
文章标题:C#深度学习の接口传参(interface)-----接口的妙用
文章链接:http://soscw.com/index.php/essay/100102.html