Go Channel Practice III - Leaky Bucket
设计模式 - 单例模式

设计模式 - 抽象工厂模式

violet posted @ Jul 07, 2020 05:40:48 AM in 笔记 with tags Design Pattern , 210 阅读

意图:提供一个创建一系列相关或相互依赖对象的接口,而无需指定它们具体的类。

主要解决:主要解决接口选择的问题。

何时使用:系统的产品有多于一个的产品族,而系统只消费其中某一族的产品。

如何解决:在一个产品族里面,定义多个产品。

关键代码:在一个工厂里聚合多个同类产品。

 

package main

import (
	"fmt"
)

type ShapeWithColor struct {
}

type Shape interface {
	Draw()
}

type Color interface {
	Fill()
}

type Rectangle struct{}
type Square struct{}
type Circle struct{}

type Red struct{}
type Green struct{}
type Blue struct{}

func (r *Rectangle) Draw() {
	fmt.Println("rectangle draw")
}

func (s *Square) Draw() {
	fmt.Println("square draw")
}

func (c *Circle) Draw() {
	fmt.Println("circle draw")
}

func (r *Red) Fill() {
	fmt.Println("fill in red")
}

func (g *Green) Fill() {
	fmt.Println("fill in green")
}

func (b *Blue) Fill() {
	fmt.Println("fill in blue")
}

func (s *ShapeWithColor) GetColor(color string) Color {
	switch color {
	case "red":
		return &Red{}
	case "green":
		return &Green{}
	case "blue":
		return &Blue{}
	}
	return nil
}

func (s *ShapeWithColor) GetShape(str string) Shape {
	switch str {
	case "circle":
		return &Circle{}
	case "rectangle":
		return &Rectangle{}
	case "square":
		return &Square{}
	}

	return nil
}

func main() {
	instance := &ShapeWithColor{}

	shape1 := instance.GetShape("circle")
	shape1.Draw()

	color1 := instance.GetColor("red")
	color1.Fill()

	shape2 := instance.GetShape("square")
	shape2.Draw()

	color2 := instance.GetColor("green")
	color2.Fill()

	shape3 := instance.GetShape("rectangle")
	shape3.Draw()

	color3 := instance.GetColor("blue")
	color3.Fill()
}
  • 无匹配

登录 *


loading captcha image...
(输入验证码)
or Ctrl+Enter