设计模式 - 服务定位器模式

栏目: IT技术 · 发布时间: 4年前

内容简介:服务定位器模式(Service Locator Pattern)用在我们想使用 JNDI 查询定位各种服务的时候。考虑到为某个服务查找 JNDI 的代价很高,服务定位器模式充分利用了缓存技术。在首次请求某个服务时,服务定位器在 JNDI 中查找服务,并缓存该服务对象。当再次请求相同的服务时,服务定位器会在它的缓存中查找,这样可以在很大程度上提高应用程序的性能。以下是这种设计模式的实体。

服务定位器模式(Service Locator Pattern)用在我们想使用 JNDI 查询定位各种服务的时候。考虑到为某个服务查找 JNDI 的代价很高,服务定位器模式充分利用了缓存技术。在首次请求某个服务时,服务定位器在 JNDI 中查找服务,并缓存该服务对象。当再次请求相同的服务时,服务定位器会在它的缓存中查找,这样可以在很大程度上提高应用程序的性能。以下是这种 设计模式 的实体。

  • 服务(Service) - 实际处理请求的服务。对这种服务的引用可以在 JNDI 服务器中查找到。
  • Context / 初始的 Context - JNDI Context 带有对要查找的服务的引用。
  • 服务定位器(Service Locator) - 服务定位器是通过 JNDI 查找和缓存服务来获取服务的单点接触。
  • 缓存(Cache) - 缓存存储服务的引用,以便复用它们。
  • 客户端(Client) - Client 是通过 ServiceLocator 调用服务的对象。
package main

import "fmt"

type Service interface {
	GetName() string
	Execute()
}

type Service1 struct{}

func (s *Service1) Execute() {
	fmt.Println("Executing service1")
}

func (s *Service1) GetName() string {
	return "Service1"
}

type Service2 struct{}

func (s *Service2) Execute() {
	fmt.Println("Executing service2")
}

func (s *Service2) GetName() string {
	return "Service2"
}

type InitContext struct{}

func (i *InitContext) Lookup(jndiName string) Service {
	if jndiName == "service1" {
		fmt.Println("looking up and creating a new service1 object")
		return &Service1{}
	}
	if jndiName == "service2" {
		fmt.Println("looking up and creating a new service2 object")
		return &Service2{}
	}
	return nil
}

type Cache struct {
	Services map[string]Service
}

func NewCache() *Cache {
	return &Cache{
		Services: map[string]Service{},
	}
}

func (c *Cache) GetService(serviceName string) Service {
	if v, ok := c.Services[serviceName]; ok {
		fmt.Println("return cached service: ", serviceName)
		return v
	}
	return nil
}

func (c *Cache) AddService(name string, service Service) {
	c.Services[name] = service
}

type ServiceLocator struct {
	Cache *Cache
}

func NewServiceLocator() *ServiceLocator {
	return &ServiceLocator{
		Cache: NewCache(),
	}
}

func (s *ServiceLocator) GetService(jndiName string) Service {
	service := s.Cache.GetService(jndiName)
	if service != nil {
		return service
	}
	// create a new service1
	context := &InitContext{}
	service = context.Lookup(jndiName)
	s.Cache.AddService(jndiName, service)
	return service
}

func main() {
	locator := NewServiceLocator()
	service := locator.GetService("service1")
	service.Execute()

	service = locator.GetService("service2")
	service.Execute()

	service = locator.GetService("service1")
	service.Execute()

	service = locator.GetService("service2")
	service.Execute()
}

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持 码农网

查看所有标签

猜你喜欢:

本站部分资源来源于网络,本站转载出于传递更多信息之目的,版权归原作者或者来源机构所有,如转载稿涉及版权问题,请联系我们

任性

任性

电子工业出版社 / 2015-10-1 / 49.00

《任性:互联网语言表达的调性和技巧》是一本深度介绍互联网调性的书,也是从社会化媒体运作的角度较为系统地讲解互联网语言表达的书,它以独特的视角,从技术、需求和表现形式三种驱动力展开,从理论、策略、方法、技巧、实践等角度详细解析了互联网表达的变化和社会媒体的运营。《任性:互联网语言表达的调性和技巧》适合互联网从业人员阅读。一起来看看 《任性》 这本书的介绍吧!

MD5 加密
MD5 加密

MD5 加密工具

HEX HSV 转换工具
HEX HSV 转换工具

HEX HSV 互换工具