Leetcode - Index Pairs of a String
Go Channel Practice IV - Token Bucket

设计模式 - 工厂模式

violet posted @ Jun 27, 2020 01:53:47 AM in 读书笔记 with tags Design Pattern , 265 阅读

意图:定义一个创建对象的接口,让其子类自己决定实例化哪一个工厂类,工厂模式使其创建过程延迟到子类进行。

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

何时使用:我们明确地计划不同条件下创建不同实例时。

如何解决:让其子类实现工厂接口,返回的也是一个抽象的产品。

 

package main

import (
    "fmt"
)

type Shape interface {
    Draw()
}

type Rectangle struct{}

type Square struct{}

type Circle 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 GetShape(str string) Shape {
    switch str {
    case "circle":
        return &Circle{}
    case "rectangle":
        return &Rectangle{}
    case "square":
        return &Square{}
    }

    return nil
}

func main() {
    shape1 := GetShape("rectangle")
    shape1.Draw()

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

    shape3 := GetShape("circle")
    shape3.Draw()
}


  • 无匹配
fiyona cha 说:
Jan 01, 2023 03:32:54 PM

A design pattern is a general repeatable solution to a commonly occurring problem in software design. The factory design pattern is a creational design pattern that separates the process of object creation from its implementation. This allows for new object types to be created without having to modify the code that uses them. The factory method pattern best cbd gummies is a common implementation of the factory design pattern.


登录 *


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