当前位置: 移动技术网 > IT编程>数据库>Redis > Go基础学习-接口设计原则(开闭原则、依赖倒装原则)

Go基础学习-接口设计原则(开闭原则、依赖倒装原则)

2020年07月17日  | 移动技术网IT编程  | 我要评论

接口设计原则

  • 开闭原则
    在这里插入图片描述
//接口设计的开闭原则(以银行业务为例)

//AbstractBanker 抽象一个AbstractBanker业务员
type AbstractBanker interface {
	DoBusiness()  //抽象的接口 业务接口
}
//实现一个架构层(基于抽象的接口来封装 ,就是在不知道具体有哪些Banker的情况下)
func BankerBusi(a AbstractBanker){
	a.DoBusiness() //多态的现象
}
//SaveBanker 存款的Banker
type SaveBanker struct {
}
//TransBanker 转账的Banker
type TransBanker struct {
}
func (s *SaveBanker)DoBusiness(){
	fmt.Println("存款业务")
}
func (s *TransBanker)DoBusiness(){
	fmt.Println("转账业务")
}
func main(){
	BankerBusi(&SaveBanker{})
	BankerBusi(&TransBanker{})
}
  • 依赖倒装原则
    在这里插入图片描述

//-------------------
//抽象层
//-------------------
type Car interface {
	Run()
}
type Driver interface {
	Drive(car Car)
}

//-------------------
//实现层
//-------------------
//car
type Benc struct {}
func (b *Benc)Run(){}

type BMW struct {}
func (b *BMW)Run(){}

type Fent struct {}
func (f *Fent)Run(){}

//driver
type ZhanS struct {}
func (f *ZhanS)Drive(car Car){
	car.Run()
}

type LiS struct {}
func (z *LiS)Drive(car Car){
	car.Run()
}

type WanW struct {}
func (f *WanW)Drive(car Car){
	car.Run()
}
//-------------------
//业务逻辑层
//-------------------
func main(){
	// 业务1:ZhanS开奔驰
	var z ZhanS
	var fentian Car
	fentian=&Fent{}  //多态
	z.Drive(fentian)
}
//模拟组装2台电脑

//------------------------
//抽象层:
//有显卡Card 方法:display()
//有内存Memory storage()
//Cpu calcalate()
//------------------------


//------------------------
//实现层:
//有Intel公司  产品:Card Memory Cpu
//Kingston公司 产品:Memory
//NVIDIA公司  产品:Card
//------------------------

//------------------------
//逻辑层:
//组装Intel系列的电脑 并运行
//组装Intel Cpu、Kingston Memory、NVIDIA Card混合的电脑并运行
//------------------------

//------------抽象层------------
type Card interface {
	Display()
}
type Memory interface {
	Storage()
}
type Cpu interface {
	Calcalate()
}


type Computer struct {
	ItemCard Card
	ItemMemory Memory
	ItemCpu Cpu
}

//NewComputer  初始化一个computer类对象
func NewComputer(cpu Cpu,card Card,memory Memory)(c *Computer){
	c=&Computer{        //多态性
		ItemCard: card,
		ItemCpu: cpu,
		ItemMemory: memory,
	}
	return
}
func (c *Computer)Work(){
	c.ItemCard.Display()
	c.ItemMemory.Storage()
	c.ItemCpu.Calcalate()
}
//------------实现层------------
type IntelCpu struct {

}
func (i *IntelCpu)Calcalate(){

}
type IntelCard struct {

}
func (i *IntelCard)Display(){

}
type IntelMemory struct {

}
func (i *IntelMemory)Storage(){

}
type KingMemory struct {

}
func (k *KingMemory)Storage(){

}
type NVIDCard struct {

}
func (n *NVIDCard)Display(){

}


//------------逻辑层------------
func main(){
	//组装Intel系列的电脑 并运行
	intelComputer:=NewComputer(&IntelCpu{},&IntelCard{},&IntelMemory{})
	intelComputer.Work()
	//组装Intel Cpu、Kingston Memory、NVIDIA Card混合的电脑并运行
	mixComputer:=NewComputer(&IntelCpu{},&NVIDCard{},&KingMemory{})
	mixComputer.Work()
}

本文地址:https://blog.csdn.net/wzb_wzt/article/details/107380699

如对本文有疑问, 点击进行留言回复!!

相关文章:

验证码:
移动技术网