接口设计原则
- 开闭原则
type AbstractBanker interface {
DoBusiness()
}
func BankerBusi(a AbstractBanker){
a.DoBusiness()
}
type SaveBanker struct {
}
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)
}
type Benc struct {}
func (b *Benc)Run(){}
type BMW struct {}
func (b *BMW)Run(){}
type Fent struct {}
func (f *Fent)Run(){}
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(){
var z ZhanS
var fentian Car
fentian=&Fent{}
z.Drive(fentian)
}
type Card interface {
Display()
}
type Memory interface {
Storage()
}
type Cpu interface {
Calcalate()
}
type Computer struct {
ItemCard Card
ItemMemory Memory
ItemCpu Cpu
}
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(){
intelComputer:=NewComputer(&IntelCpu{},&IntelCard{},&IntelMemory{})
intelComputer.Work()
mixComputer:=NewComputer(&IntelCpu{},&NVIDCard{},&KingMemory{})
mixComputer.Work()
}