【设计模式】第12节:结构型模式之“外观模式”

本文介绍了门面模式,如何通过创建HomeTheaterFacade来封装和统一家庭影院中的各种播放设备操作,如Projecter、DVDPlayer和SoundSystem,从而简化用户交互。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

一、简介

门面模式,也叫外观模式,英文全称是Facade Design Pattern。门面模式为子系统提供一组统一的接口,定义一组高层接口让子系统更易用。

目的:简化复杂系统的交互方式

特点:提供一个统一的交互接口

二、UML类图

请添加图片描述

三、案例

以下案例是家庭影院,家庭影院中有各种播放设备,如DVD、音响等,整体对外提供看电影和关闭的功能。

package main

import "fmt"

type Projecter struct {
}

func (Projecter) On() {
    fmt.Println("Turning on the projecter...")
}

func (Projecter) Off() {
    fmt.Println("Turning off the projecter...")
}

type DVDPlayer struct {
}

func (DVDPlayer) Play() {
    fmt.Println("Playing the DVDPlayer...")
}

func (DVDPlayer) Stop() {
    fmt.Println("Stopping the DVDPlayer...")
}

type SoundSystem struct {
}

func (SoundSystem) On() {
    fmt.Println("Turning on the sound system...")
}

func (SoundSystem) Off() {
    fmt.Println("Turning off the sound system...")
}

type HomeTheaterFacade struct {
    Projecter Projecter
    DVDPlayer DVDPlayer
    SoundSystem SoundSystem
}

func NewHomeTheaterFacade(projecter Projecter, dvdPlayer DVDPlayer, soundSystem SoundSystem) HomeTheaterFacade {
    homeTheaterFacade := HomeTheaterFacade{}
    homeTheaterFacade.Projecter = projecter
    homeTheaterFacade.DVDPlayer = dvdPlayer
    homeTheaterFacade.SoundSystem = soundSystem
    return homeTheaterFacade
}

func (htf HomeTheaterFacade) WatchMovie() {
    htf.Projecter.On()
    htf.DVDPlayer.Play()
    htf.SoundSystem.On()
}

func (htf HomeTheaterFacade) StopMovie() {
    htf.Projecter.Off()
    htf.DVDPlayer.Stop()
    htf.SoundSystem.Off()
}

func main() {
    projecter := Projecter{}
    dvdPlayer := DVDPlayer{}
    soundSystem := SoundSystem{}
   	homeTheaterFacade := NewHomeTheaterFacade(projecter, dvdPlayer, soundSystem)
  	homeTheaterFacade.WatchMovie()
  	homeTheaterFacade.StopMovie()
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值