JustNote
  • Introduction
  • DesignPattern
    • 七大原则
      • 开闭原则(OCP)
      • 依赖倒置原则(DIP)
      • 单一职责原则(SRP)
      • 接口隔离原则(ISP)
      • 迪米特法则(LoD)
      • 里氏代换原则(LSP)
      • 合成复用原则(CRP)
    • 创建型模式
      • 简单工厂模式
      • 工厂方法模式
      • 抽象工厂模式
      • 建造者模式
      • 单例模式
      • 原型模式
    • 结构型模式
      • 外观模式
      • 装饰模式
      • 适配器模式
      • 享元模式
      • 组合模式
      • 桥接模式
      • 代理模式
    • 行为型模式
      • 模板方法模式
      • 迭代器模式
      • 策略模式
      • 解释器模式
      • 观察者模式
      • 备忘录模式
      • 命令模式
      • 中介者模式
      • 责任链模式
      • 访问者模式
      • 状态模式
  • Java
    • Java Core
      • JVM 如何加载类
      • JVM 垃圾回收
      • JVM G1GC
      • JVM G1GC Q&A
      • JVM 与 Hbase
      • JVM ZGC Overview
      • JVM ZGC 内存管理
      • JVM ZGC 线程
      • JVM ZGC 垃圾回收
      • JVM ZGC 日志分析
      • JVM ZGC 参数调优
    • checkstyle
  • Golang
    • 源码阅读
      • Goroutines
      • Channel
    • gRPC
      • 1、快速开始
      • 2、什么是gRPC
      • 3、gRPC概念梳理
      • 4、基于Golang的gRPC入门
      • 5、gRPC组件ProtocolBuffers介绍
      • 6、gRPC组件Http 2.0
      • 7、错误处理和Debug
      • 8、gRPC身份验证
      • 9、服务注册与发现
      • 10、gRPC与gRPC Gateway
      • 11、gRPC与分布式链路追踪
  • Scala
    • 数据结构与算法
      • 数组
      • 队列
    • 函数式编程
      • 高阶函数
      • 偏函数
    • Immutable Collection
      • List
    • Mutable Collection
      • Array
    • 常见函数操作
      • A
        • aggregate
        • andThen
        • appended
        • appendedAll
      • C
        • chain
        • collect
        • collectFirst
        • combinations
        • compose
        • concat
        • cond
        • condOpt
        • const
        • contains
        • containsSlice
        • copyToArray
        • corresponds
        • count
        • curried
      • D
        • diff
        • distinct
        • distinctBy
        • drop
        • dropRight
        • dropWhile
      • E
        • empty(PartialFunction)
        • empty(collections)
        • endsWith
        • exists
      • F
        • fill
        • filter
        • filterKeys
        • filterNot
        • find
        • findLast
        • flatMap
        • flatten
        • fold
        • foldLeft
        • foldRight
        • forall
        • foreach
        • fromFunction
      • G
        • getOrElse (Map)
        • getOrElse (Option)
        • groupBy
        • groupMap
        • groupMapReduce
        • grouped
      • H
        • head
        • headOption
      • I
        • indexOf
        • indexOfSlice
        • indexWhere
        • indices
        • init
        • inits
        • intersect
        • isDefinedAt (Map)
        • isDefinedAt (Seq)
        • isEmpty
        • isTraversableAgain
      • K
        • keys
      • L
        • last
        • lastIndexOf
        • lastIndexOfSlice
        • lastIndexWhere
        • lastOption
        • length
        • lift
      • M
        • map
        • mapConserve
        • mapValues
        • max
        • maxBy
        • maxByOption
        • maxOption
        • min
        • minBy
        • minByOption
        • minOption
        • mkString
      • N
        • nonEmpty
      • O
        • orElse
      • P
        • padTo
        • par
        • partition
        • partitionMap
        • patch
        • permutations
        • prefixLength
        • prepended
        • prependedAll
        • product
      • R
        • range
        • reduce
        • reduceLeft
        • reduceLeftOption
        • reduceOption
        • reduceRight
        • reduceRightOption
        • reverse
        • reverseIterator
        • reverseMap
        • runWith
      • S
        • sameElements
        • scan
        • scanLeft
        • scanRight
        • search
        • segmentLength
        • size
        • slice
        • sliding
        • sortBy
        • sortWith
        • sorted
        • span
        • splitAt
        • startsWith
        • sum
      • T
        • tabulate
        • tail
        • tails
        • take
        • takeRight
        • takeWhile
        • transpose
        • tupled
      • U
        • unfold
        • union
        • unlift
        • untupled
        • unzip
        • unzip3
        • updated
      • V
        • values
        • view
      • W
        • withFilter
        • withDefault
        • withDefaultValue
      • Z
        • zip
        • zipAll
        • zipWithIndex
      • map
      • flatmap
      • filter
      • reduceLeft
      • foldLeft
    • Futures
      • Method with future as return type
      • Non blocking future result
      • Chain futures using flatMap
      • Chain futures using for comprehension
      • Future Option with for comprehension
      • Future Option with map
      • Composing Futures
      • Future Sequence
      • Future Traverse
      • Future foldLeft
      • Future reduceLeft
      • Future firstCompletedOf
      • Future zip
      • Future zipWith
      • Future andThen
      • Future configure threadpool
      • Future recover
      • Future recoverWith
      • Future fallbackTo
      • Future promise
    • Akka
  • Algorithm
  • Docker
  • Kubernetes
    • 二进制安装kubernetes
      • 00.从零开始
  • Architecture
    • Infrastructure
      • Opentracing
      • Jaeger && ZipKin
      • SkyWalking
      • Consul
      • Envoy
      • Service Mesh
      • Service Mesh: Istio 详解
      • Service Mesh: 基于 Istio 的落地实践(一)
    • CAS
      • CAS Server
      • CAS Service Management
      • CAS 集成LDAP
      • CAS 集成gitlab
      • CAS SSO & SLO
      • CAS Gitbook
    • xCAT
  • Netty
  • DDD
  • Reactive Programming
    • Reactor
      • Publisher
      • Subscriber
      • Subscription
      • Processor
    • WebFlux
  • Gitlab
    • Git Hook
  • CICD
    • Jenkins
      • Kubectl
Powered by GitBook
On this page
  • 适用场景
  • 优点
  • 缺点
  • 扩展
  • Golang Demo
  • Java Demo
  • UML
  • 补充另一个版本的Java/Scala Demo 以及源码解析
  • Java Demo_
  • Scala Demo
  • UML_
  • 源码解析

Was this helpful?

  1. DesignPattern
  2. 结构型模式

享元模式

   享元模式(Flyweight Pattern):运用共享技术有效地支持大量细粒度对象的复用。系统只使用少量的对象,而这些对象都很相似,状态变化很小,可以实现对象的多次复用。由于享元模式要求能够共享的对象必须是细粒度对象,因此它又称为轻量级模式,它是一种对象结构型模式。提供了减少对象数量从而改善应用所需的对象结构的的方式

适用场景

  • 尝尝应用于系统的底层开发,以便解决系统的性能问题。例如数据库的连接池。

  • 系统有大量的相似对象,需要缓冲池的场景。

优点

  • 减少对象的创建,降低内存中对象的数量,降低系统的内存,提高效率

  • 减少内存之外的其他资源

缺点

  • 关注内/外部状态、关注线程安全问题

  • 使系统、程序逻辑复杂化

扩展

  • 内部状态,不随着环境的改变而改变,位于享元对象的内部。

  • 外部状态,因为环境的改变而改变,一般位于享元模式的外部。

通常可以理解,内部状态就是享元对象的属性。

Golang Demo

package flyweight

import (
    "fmt"
)

type Employee interface {
    report()
}

type Manager struct {
    title         string
    department    string
    reportContent string
}

func (m Manager) report() {
    fmt.Println(m.reportContent)
}

func NewManager(department string) Manager {
    return Manager{
        title:      "部门经理",
        department: department,
    }
}

func (m *Manager) SetReportContent(reportContent string) {
    m.reportContent = reportContent
}

type EmployeeFactory struct {
    employeeMap map[string]Employee
}

func NewEmployeeFactory() *EmployeeFactory {
    return &EmployeeFactory{
        employeeMap: make(map[string]Employee),
    }
}

func (e *EmployeeFactory) getManager(department string) Employee {

    var manager Manager
    if v, ok := e.employeeMap[department]; !ok {
        manager = NewManager(department)
        fmt.Println("创建部门经理:" + department)
    } else {
        manager = v.(Manager)
    }
    reportContent := department + "部门汇报:此次报告的主要内容是......"
    manager.SetReportContent(reportContent)
    fmt.Println(" 创建报告:" + reportContent)
    e.employeeMap[department] = manager
    return manager
}
package flyweight

import (
    "math/rand"
    "testing"
    "time"
)

func Test(t *testing.T) {
    departments := []string{"RD", "QA", "PM", "BD"}
    rand.Seed(time.Now().UnixNano())
    employeeFactory := NewEmployeeFactory()
    for i := 0; i < 10; i++ {
        department := departments[int(rand.Float32()*4)]
        manager := employeeFactory.getManager(department).(Manager)
        manager.report()
    }
}

Java Demo

package tech.selinux.design.pattern.structural.flyweight;

public interface Employee {
  void report();
}
package tech.selinux.design.pattern.structural.flyweight;

public class Manager implements Employee {
  @Override
  public void report() {
    System.out.println(reportContent);
  }

  private String title = "部门经理";
  private String department;
  private String reportContent;

  public void setReportContent(String reportContent) {
    this.reportContent = reportContent;
  }

  public Manager(String department) {
    this.department = department;
  }
}
package tech.selinux.design.pattern.structural.flyweight;

import java.util.HashMap;
import java.util.Map;

public class EmployeeFactory {
  private static final Map<String, Employee> EMPLOYEE_MAP = new HashMap<String, Employee>();

  public static Employee getManager(String department) {
    Manager manager = (Manager) EMPLOYEE_MAP.get(department);

    if (manager == null) {
      manager = new Manager(department);
      System.out.print("创建部门经理:" + department);
      String reportContent = department + "部门汇报:此次报告的主要内容是......";
      manager.setReportContent(reportContent);
      System.out.println(" 创建报告:" + reportContent);
      EMPLOYEE_MAP.put(department, manager);
    }
    return manager;
  }
}
package tech.selinux.design.pattern.structural.flyweight;

public class Test {
  private static final String departments[] = {"RD", "QA", "PM", "BD"};

  public static void main(String[] args) {
    for (int i = 0; i < 10; i++) {
      String department = departments[(int) (Math.random() * departments.length)];
      Manager manager = (Manager) EmployeeFactory.getManager(department);
      manager.report();
    }
  }
}

这里面,title 一直不会发生变化,就是内部状态,而department需要通过setter方法来使用。就可以理解为title是内部状态,而department使外部状态。

UML

补充另一个版本的Java/Scala Demo 以及源码解析

Java Demo_

Scala Demo

UML_

源码解析

Previous适配器模式Next组合模式

Last updated 5 years ago

Was this helpful?

享元模式UML