什么是门面设计模式?

发布于 2024-10-21 00:08:47 字数 109 浏览 5 评论 0原文

Facade 是一个包含许多其他类的类吗?

是什么让它成为设计模式?对我来说,这就像一堂普通的课。

你能给我解释一下这个Facade模式吗?

Is Facade a class which contains a lot of other classes?

What makes it a design pattern? To me, it is like a normal class.

Can you explain to me this Facade pattern?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(20

欢你一世 2024-10-28 00:08:47

设计模式是解决重复出现的问题的常用方法。所有设计模式中的类都只是普通的类。重要的是它们的结构以及它们如何协同工作以尽可能最好的方式解决给定的问题。

外观设计模式简化了复杂系统的界面;因为它通常由构成复杂系统子系统的所有类组成。

外观使用户免受系统复杂细节的影响,并为他们提供了易于使用简化视图。它还将使用系统的代码与子系统的细节解耦,使得以后修改系统变得更加容易。

http://www.dofactory.com/Patterns/PatternFacade.aspx

http://www.blackwasp.co.uk/Facade.aspx

另外,学习设计时重要的是什么模式是能够识别哪种模式适合您给定的问题,然后适当地使用它。滥用模式或仅仅因为您知道模式就试图将其适应某些问题是很常见的事情。在学习\使用设计模式时要注意这些陷阱。

A design pattern is a common way of solving a recurring problem. Classes in all design patterns are just normal classes. What is important is how they are structured and how they work together to solve a given problem in the best possible way.

The Facade design pattern simplifies the interface to a complex system; because it is usually composed of all the classes which make up the subsystems of the complex system.

A Facade shields the user from the complex details of the system and provides them with a simplified view of it which is easy to use. It also decouples the code that uses the system from the details of the subsystems, making it easier to modify the system later.

http://www.dofactory.com/Patterns/PatternFacade.aspx

http://www.blackwasp.co.uk/Facade.aspx

Also, what is important while learning design patterns is to be able to recognize which pattern fits your given problem and then using it appropriately. It is a very common thing to misuse a pattern or trying to fit it to some problem just because you know it. Be aware of those pitfalls while learning\using design patterns.

情独悲 2024-10-28 00:08:47

Wikipedia 有一个很好的外观模式示例。

/* Complex parts */

class CPU {
    public void freeze() { ... }
    public void jump(long position) { ... }
    public void execute() { ... }
}

class Memory {
    public void load(long position, byte[] data) { ... }
}

class HardDrive {
    public byte[] read(long lba, int size) { ... }
}

/* Facade */

class ComputerFacade {
    private CPU processor;
    private Memory ram;
    private HardDrive hd;

    public ComputerFacade() {
        this.processor = new CPU();
        this.ram = new Memory();
        this.hd = new HardDrive();
    }

    public void start() {
        processor.freeze();
        ram.load(BOOT_ADDRESS, hd.read(BOOT_SECTOR, SECTOR_SIZE));
        processor.jump(BOOT_ADDRESS);
        processor.execute();
    }
}

/* Client */

class You {
    public static void main(String[] args) {
        ComputerFacade computer = new ComputerFacade();
        computer.start();
    }
}

Wikipedia has a great example of Facade pattern.

/* Complex parts */

class CPU {
    public void freeze() { ... }
    public void jump(long position) { ... }
    public void execute() { ... }
}

class Memory {
    public void load(long position, byte[] data) { ... }
}

class HardDrive {
    public byte[] read(long lba, int size) { ... }
}

/* Facade */

class ComputerFacade {
    private CPU processor;
    private Memory ram;
    private HardDrive hd;

    public ComputerFacade() {
        this.processor = new CPU();
        this.ram = new Memory();
        this.hd = new HardDrive();
    }

    public void start() {
        processor.freeze();
        ram.load(BOOT_ADDRESS, hd.read(BOOT_SECTOR, SECTOR_SIZE));
        processor.jump(BOOT_ADDRESS);
        processor.execute();
    }
}

/* Client */

class You {
    public static void main(String[] args) {
        ComputerFacade computer = new ComputerFacade();
        computer.start();
    }
}
茶色山野 2024-10-28 00:08:47

正如前面的答案中所解释的,它为消费客户端提供了一个简单的接口。
例如:“观看 ESPN”是预期功能。但它涉及几个步骤,例如:

  1. 如果需要,打开电视;
  2. 检查卫星/有线功能;
  3. 如果需要,请切换到 ESPN。

但外观会简化这一点,只向客户端提供“观看 ESPN”功能。

As explained in the previous answer it provides a simple interface to the consuming client.
For example: "watch ESPN" is the intended function. But it involves several steps like:

  1. Switch on TV if required;
  2. Check for satellite/cable functioning;
  3. Switch to ESPN if required.

But the facade will simplify this and just provide "watch ESPN" function to the client.

又爬满兰若 2024-10-28 00:08:47

外观隐藏了系统的复杂性,并为客户端提供了一个接口,客户端可以从该接口访问系统。

public class Inventory {
public String checkInventory(String OrderId) {
    return "Inventory checked";
}
}

public class Payment {
public String deductPayment(String orderID) {
    return "Payment deducted successfully";
}
}


public class OrderFacade {
private Payment pymt = new Payment();
private Inventory inventry = new Inventory();

public void placeOrder(String orderId) {
    String step1 = inventry.checkInventory(orderId);
    String step2 = pymt.deductPayment(orderId);
    System.out
            .println("Following steps completed:" + step1
                    + " & " + step2);
   }
}

public class Client {
       public static void main(String args[]){
         OrderFacade orderFacade = new OrderFacade();
         orderFacade.placeOrder("OR123456");
         System.out.println("Order processing completed");
       }
  }

Facade hides the complexities of the system and provides an interface to the client from where the client can access the system.

public class Inventory {
public String checkInventory(String OrderId) {
    return "Inventory checked";
}
}

public class Payment {
public String deductPayment(String orderID) {
    return "Payment deducted successfully";
}
}


public class OrderFacade {
private Payment pymt = new Payment();
private Inventory inventry = new Inventory();

public void placeOrder(String orderId) {
    String step1 = inventry.checkInventory(orderId);
    String step2 = pymt.deductPayment(orderId);
    System.out
            .println("Following steps completed:" + step1
                    + " & " + step2);
   }
}

public class Client {
       public static void main(String args[]){
         OrderFacade orderFacade = new OrderFacade();
         orderFacade.placeOrder("OR123456");
         System.out.println("Order processing completed");
       }
  }
末が日狂欢 2024-10-28 00:08:47

简短的解释:

  • 外观模式为一组接口提供了一个统一的接口
    在一个子系统中。
  • Facade定义了一个高层接口,使得子系统
    更容易使用。

尝试理解有和没有 Façade 的场景:
如果您想将钱从 account1 转移到 account2,那么要调用的两个子系统是从 account1 提款和向 account2 存款。

有和没有立面

A short and simple explanation:

  • Facade pattern provides a unified interface to a set of interface(s)
    in a subsystem.
  • Facade defines a higher-level interface that makes the subsystem
    easier to use.

Try to understand the scenario with and without Façade:
If you want to transfer the money from accout1 to account2 then the two subsystems to be invoked are, withdraw from account1 and deposit to account2.

with and without facade

药祭#氼 2024-10-28 00:08:47

外观不应该被描述为包含许多其他类的类。它实际上是此类的接口,应该使类的使用更容易,否则外观类就没用了。

A facade should not be described as a class which contains a lot of other classes. It is in fact a interface to this classes and should make the usage of the classes easier otherwise the facade class is useless.

清引 2024-10-28 00:08:47

关于您的询问:

Facade 是一个包含很多其他类的类吗?

是的。它是应用程序中许多子系统的包装。

是什么使它成为一种设计模式?对我来说,这就像一个普通的班级

所有设计模式也都是普通的类。 @Unmesh Kondolikar 正确回答了这个问题。

你能给我解释一下这个外观吗,我是设计模式的新手。

根据 GoF 的说法,Facade 设计模式定义为:

为子系统中的一组接口提供统一的接口。外观模式定义了一个更高级别的接口,使子系统更易于使用

外观 模式通常用于以下情况:

  1. 需要一个简单的接口来访问复杂的系统。
  2. 分层软件的每个级别都需要一个入口点。

让我们以 cleartrip 网站为例。

该网站提供预订

  1. 航班
  2. 酒店
  3. 航班 + 酒店

的选项 代码片段:

import java.util.*;

public class TravelFacade{
    FlightBooking flightBooking;
    TrainBooking trainBooking;
    HotelBooking hotelBooking;

    enum BookingType {
        Flight,Train,Hotel,Flight_And_Hotel,Train_And_Hotel;
    }; 
    
    public TravelFacade(){
        flightBooking = new FlightBooking();
        trainBooking = new TrainBooking();
        hotelBooking = new HotelBooking();        
    }
    public void book(BookingType type, BookingInfo info){
        switch(type){
            case Flight:
                // book flight;
                flightBooking.bookFlight(info);
                return;
            case Hotel:
                // book hotel;
                hotelBooking.bookHotel(info);
                return;
            case Train:
                // book Train;
                trainBooking.bookTrain(info);
                return;
            case Flight_And_Hotel:
                // book Flight and Hotel
                flightBooking.bookFlight(info);
                hotelBooking.bookHotel(info);
                return;
             case Train_And_Hotel:
                // book Train and Hotel
                trainBooking.bookTrain(info);
                hotelBooking.bookHotel(info);
                return;                
        }
    }
}
class BookingInfo{
    String source;
    String destination;
    Date    fromDate;
    Date     toDate;
    List<PersonInfo> list;
}
class PersonInfo{
    String name;
    int       age;
    Address address;
}
class Address{

}
class FlightBooking{
    public FlightBooking(){
    
    }
    public void bookFlight(BookingInfo info){
    
    }
}
class HotelBooking{
    public HotelBooking(){
    
    }
    public void bookHotel(BookingInfo info){
    
    }
}
class TrainBooking{
    public TrainBooking(){
    
    }
    public void bookTrain(BookingInfo info){
    
    }
}

说明:

  1. FlightBooking、TrainBooking 和 HotelBooking code> 是大型系统的不同子系统:TravelFacade


  2. TravelFacade 提供了一个简单的界面来预订以下选项之一

     航班预订
     火车票预订 
     酒店预订
     机票+酒店预订 
     火车+酒店预订
    
  3. TravelFacade 的预订 API 内部调用子系统的以下 API

     FlightBooking.bookFlight
     trainBooking.bookTrain(信息);
     hotelBooking.bookHotel(信息);
    
  4. 通过这种方式,TravelFacade 提供了更简单、更容易的 API,而无需暴露子系统 API。

Regarding your queries:

Is Facade a class which contains a lot of other classes?

Yes. It is a wrapper for many sub-systems in application.

What makes it a design pattern? For me, it is like a normal class

All design patterns too are normal classes. @Unmesh Kondolikar rightly answered this query.

Can you explain me about this Facade, I am new to design patterns.

According to GoF, Facade design pattern is defind as :

Provide a unified interface to a set of interfaces in a subsystem. Facade Pattern defines a higher-level interface that makes the subsystem easier to use

The Facade pattern is typically used when:

  1. A simple interface is required to access a complex system.
  2. Need an entry point to each level of layered software.

Let's take a real word example of cleartrip website.

This website provides options to book

  1. Flights
  2. Hotels
  3. Flights + Hotels

Code snippet:

import java.util.*;

public class TravelFacade{
    FlightBooking flightBooking;
    TrainBooking trainBooking;
    HotelBooking hotelBooking;

    enum BookingType {
        Flight,Train,Hotel,Flight_And_Hotel,Train_And_Hotel;
    }; 
    
    public TravelFacade(){
        flightBooking = new FlightBooking();
        trainBooking = new TrainBooking();
        hotelBooking = new HotelBooking();        
    }
    public void book(BookingType type, BookingInfo info){
        switch(type){
            case Flight:
                // book flight;
                flightBooking.bookFlight(info);
                return;
            case Hotel:
                // book hotel;
                hotelBooking.bookHotel(info);
                return;
            case Train:
                // book Train;
                trainBooking.bookTrain(info);
                return;
            case Flight_And_Hotel:
                // book Flight and Hotel
                flightBooking.bookFlight(info);
                hotelBooking.bookHotel(info);
                return;
             case Train_And_Hotel:
                // book Train and Hotel
                trainBooking.bookTrain(info);
                hotelBooking.bookHotel(info);
                return;                
        }
    }
}
class BookingInfo{
    String source;
    String destination;
    Date    fromDate;
    Date     toDate;
    List<PersonInfo> list;
}
class PersonInfo{
    String name;
    int       age;
    Address address;
}
class Address{

}
class FlightBooking{
    public FlightBooking(){
    
    }
    public void bookFlight(BookingInfo info){
    
    }
}
class HotelBooking{
    public HotelBooking(){
    
    }
    public void bookHotel(BookingInfo info){
    
    }
}
class TrainBooking{
    public TrainBooking(){
    
    }
    public void bookTrain(BookingInfo info){
    
    }
}

Explanation:

  1. FlightBooking, TrainBooking and HotelBooking are different sub-systems of large system : TravelFacade

  2. TravelFacade offers a simple interface to book one of below options

     Flight Booking
     Train Booking 
     Hotel Booking
     Flight + Hotel booking 
     Train + Hotel booking
    
  3. book API from TravelFacade internally calls below APIs of sub-systems

     flightBooking.bookFlight
     trainBooking.bookTrain(info);
     hotelBooking.bookHotel(info);
    
  4. In this way, TravelFacade provides simpler and easier API with-out exposing sub-system APIs.

傲世九天 2024-10-28 00:08:47

外观模式是许多其他接口的包装,以产生更简单的接口。

设计模式非常有用,因为它们可以解决重复出现的问题并通常简化代码。在同意使用相同模式的开发团队中,可以提高维护彼此代码时的效率和理解。

尝试阅读更多模式:

外观模式:http://www.dofactory.com/Patterns/ PatternFacade.aspx#_self1

或更一般地说:http://www.dofactory.com/模式/Patterns.aspx

The facade pattern is a wrapper of many other interfaces in a result to produce a simpler interface.

Design patterns are useful as they solve recurring problems and in general simplify code. In a team of developers who agree to use the same patterns it improves efficiency and understanding when maintaining each others code.

Try reading about more patterns:

Facade Pattern: http://www.dofactory.com/Patterns/PatternFacade.aspx#_self1

or more generally: http://www.dofactory.com/Patterns/Patterns.aspx

转瞬即逝 2024-10-28 00:08:47

Façade 模式的另一项用途是缩短团队的学习曲线。让我举个例子:

假设您的应用程序需要通过利用 Excel 提供的 COM 对象模型来与 MS Excel 进行交互。您的一位团队成员了解所有 Excel API,并在其之上创建了一个 Facade,它满足了应用程序的所有基本场景。团队中的其他成员不需要花时间学习 Excel API。团队可以在不了解内部结构或实现场景所涉及的所有 MS Excel 对象的情况下使用外观。是不是很棒?

因此,它在复杂的子系统之上提供了一个简化且统一的界面。

One additional use of Façade pattern could be to reduce the learning curve of your team. Let me give you an example:

Let us assume that your application needs to interact with MS Excel by making use of the COM object model provided by the Excel. One of your team members knows all the Excel APIs and he creates a Facade on top of it, which fulfills all the basic scenarios of the application. No other member on the team need to spend time on learning Excel API. The team can use the facade without knowing the internals or all the MS Excel objects involved in fulfilling a scenario. Is not it great?

Thus, it provides a simplified and unified interface on top of a complex sub-system.

蹲墙角沉默 2024-10-28 00:08:47

有一个非常好的现实生活中的模式示例 - 汽车起动机

作为司机,我们只需打开钥匙,汽车就可以启动。尽可能简单。在幕后,许多其他汽车系统都参与其中(如电池、发动机、燃料等),以便汽车成功启动,但它们隐藏在启动器后面。

正如你所看到的,汽车启动器是Facade。它为我们提供了易于使用的界面,无需担心所有其他汽车系统的复杂性。

让我们总结一下:

Facade 模式简化并隐藏了大型代码块或 API 的复杂性,提供了更清晰、易于理解且易于使用的界面。

There is a very good real-life example of the pattern  - The car starter engine.

As drivers, we just turn the key on and the car get started. As simple as possible. Behind the scenes, many other car systems are involved (as battery, engine, fuel, etc.), in order the car to start successfully, but they are hidden behind the starter.

As you can see, the car starter is the Facade. It gives us easy to use interface, without worrying about the complexity of all other car systems.

Let's summarize:

The Facade pattern simplifies and hides the complexity of large code blocks or APIs, providing a cleaner, understandable and easy of use interface.

不即不离 2024-10-28 00:08:47

另一个门面的例子:
假设您的应用程序连接到数据库并在 UI 上显示结果。您可以使用外观使您的应用程序可配置,就像使用数据库或模拟对象运行一样。因此,您将对外观类进行所有数据库调用,它将读取应用程序配置并决定触发数据库查询或返回模拟对象。这样,如果数据库不可用,应用程序将变得独立于数据库。

Another example of facade:
say your application connects to database and display results on the UI. You can use facade to make your application configurable, as in run using database or with mock objects. So you will make all the database calls to the facade class, where it will read app config and decide to fire the db query or return the mock object. this way application becomes db independent in case db is unavailable.

醉酒的小男人 2024-10-28 00:08:47

外观公开了大多数被调用的简化函数,并且实现隐藏了客户端必须处理的复杂性。一般来说,实现使用多个包、类和函数。编写良好的外观使得直接访问其他类的情况很少见。例如,当我访问 ATM 并提取一些金额时。 ATM 隐藏它是直接进入所属银行还是通过外部银行的协商网络。 ATM 的行为就像一个消耗多个设备和子系统的外观,作为客户端,我不必直接处理这些设备和子系统。

A facade exposes simplified functions that are mostly called and the implementation conceals the complexity that clients would otherwise have to deal with. In general the implementation uses multiple packages, classes and function there in. Well written facades make direct access of other classes rare. For example when I visit an ATM and withdraw some amount. The ATM hides whether it is going straight to the owned bank or is it going over a negotiated network for an external bank. The ATM acts like a facade consuming multiple devices and sub-systems that as a client I do not have to directly deal with.

皇甫轩 2024-10-28 00:08:47

外观是一个功能级别介于工具包和完整应用程序之间的类,提供了包或子系统中类的简化使用。 Facade 模式的目的是提供一个使子系统易于使用的接口。
-- 摘自一书《C# 中的设计模式》。

A facade is a class with a level of functionality that lies between a toolkit and a complete application, offering a simplified usage of the classes in a package or subsystem. The intent of the Facade pattern is to provide an interface that makes a subsystem easy to use.
-- Extract from book Design Patterns in C#.

听闻余生 2024-10-28 00:08:47

Facade 讨论了将复杂的子系统封装在单个接口对象中。这减少了成功利用该子系统所需的学习曲线。它还促进子系统与其潜在的许多客户端解耦。另一方面,如果外观是子系统的唯一接入点,它将限制“高级用户”可能需要的功能和灵活性。

来源:https://sourcemaking.com/design_patterns/facade

Facade discusses encapsulating a complex subsystem within a single interface object. This reduces the learning curve necessary to successfully leverage the subsystem. It also promotes decoupling the subsystem from its potentially many clients. On the other hand, if the Facade is the only access point for the subsystem, it will limit the features and flexibility that "power users" may need.

Source: https://sourcemaking.com/design_patterns/facade

飘然心甜 2024-10-28 00:08:47

设计模式是针对软件设计中给定上下文中常见问题的通用可重用解决方案。

外观设计模式是一种结构模式,因为它定义了在类或实体之间创建关系的方式。外观设计模式用于定义更复杂子系统的简化接口。

当处理大量相互依赖的类或需要使用多种方法的类时,尤其是当它们使用复杂或难以理解时,外观模式是理想的选择。外观类是一个“包装器”,包含一组易于理解且易于使用的成员。这些成员代表外观用户访问子系统,隐藏实现细节。

当包装设计不佳但由于源代码不可用或现有接口被广泛使用而无法重构的子系统时,外观设计模式特别有用。有时,您可能决定实现多个外观来为不同目的提供功能子集。

外观模式的一个示例用途是将网站与业务应用程序集成。现有软件可能包括大量必须以特定方式访问的业务逻辑。该网站可能只需要对此业务逻辑的有限访问。例如,网站可能需要显示待售商品是否已达到库存限制水平。外观类的 IsLowStock 方法可以返回一个布尔值来指示这一点。在幕后,此方法可能隐藏了处理当前实际库存、进货库存、分配的商品以及每个商品的低库存水平的复杂性。

A design pattern is a general reusable solution to a commonly occurring problem within a given context in software design.

The Facade design pattern is a structural pattern as it defines a manner for creating relationships between classes or entities. The facade design pattern is used to define a simplified interface to a more complex subsystem.

The facade pattern is ideal when working with a large number of interdependent classes, or with classes that require the use of multiple methods, particularly when they are complicated to use or difficult to understand. The facade class is a "wrapper" that contains a set of members that are easily understood and simple to use. These members access the subsystem on behalf of the facade user, hiding the implementation details.

The facade design pattern is particularly useful when wrapping subsystems that are poorly designed but cannot be refactored because the source code is unavailable or the existing interface is widely used. Sometimes you may decide to implement more than one facade to provide subsets of functionality for different purposes.

One example use of the facade pattern is for integrating a web site with a business application. The existing software may include large amounts of business logic that must be accessed in a particular manner. The web site may require only limited access to this business logic. For example, the web site may need to show whether an item for sale has reached a limited level of stock. The IsLowStock method of the facade class could return a Boolean value to indicate this. Behind the scenes, this method could be hiding the complexities of processing the current physical stock, incoming stock, allocated items and the low stock level for each item.

挖鼻大婶 2024-10-28 00:08:47

它只是创建一个包装器来调用多个方法。
您有一个带有方法 x()y()A 类,以及带有 方法的 B 类k() 和 z()。
您想要一次调用 x, y, z,要使用 Facade 模式来做到这一点,您只需创建一个 Facade 类并创建一个方法,例如 xyz()
您无需单独调用每个方法(x、y 和 z),只需调用外观类的包装方法 (xyz()) 即可调用这些方法。

类似的模式是存储库,但它主要用于数据访问层。

Its simply creating a wrapper to call multiple methods .
You have an A class with method x() and y() and B class with method k() and z().
You want to call x, y, z at once , to do that using Facade pattern you just create a Facade class and create a method lets say xyz().
Instead of calling each method (x,y and z) individually you just call the wrapper method (xyz()) of the facade class which calls those methods .

Similar pattern is repository but it s mainly for the data access layer.

柠檬色的秋千 2024-10-28 00:08:47

所有设计模式都是以某种方式排列的一些类,以适合特定的应用程序。外观模式的目的是隐藏一个或多个操作的复杂性。您可以从 http://preciselyconcise.com/design_patterns/facade.php

All design patterns are some classes arranged in some way or other that suits a specific application. The purpose of facade pattern is to hide the complexity of an operation or operations. You can see an example and learn facade pattern from http://preciselyconcise.com/design_patterns/facade.php

风月客 2024-10-28 00:08:47

我喜欢《Eric Freeman、Elisabeth Freeman、Kathy Sierra、Bert Bates - Head First Design Patterns》一书中的示例。
例子:
假设您创建了家庭影院,最后您想看电影。所以你必须做:

        Amplifier amplifier = new Amplifier();
        CdPlayer cdPlayer = new CdPlayer();
        DvdPlayer dvdPlayer = new DvdPlayer();
        Lights lights = new Lights();
        PopcornPopper popcornPopper = new PopcornPopper();
        Projector projector = new Projector();
        Screen screen = new Screen();

        popcornPopper.turnOn();
        popcornPopper.pop();
        amplifier.turnOn();
        amplifier.setVolume(10);
        lights.turnOn();
        lights.dim(10);
        screen.up();
        dvdPlayer.turnOn();
        dvdPlayer.play();

电影结束后会发生什么?您必须以相反的顺序执行相同的操作,因此观看和结束电影的复杂性变得非常复杂。外观模式表示您可以创建一个外观并让用户只调用一个方法而不是调用所有这些方法。
让我们创建门面:

public class HomeTheatherFacade {
    Amplifier amplifier;
    DvdPlayer dvdPlayer;
    CdPlayer cdPlayer;
    Projector projector;
    Lights lights;
    Screen screen;
    PopcornPopper popcornPopper;

    public HomeTheatherFacade(Amplifier amplifier, DvdPlayer dvdPlayer, CdPlayer cdPlayer, Projector projector, Lights lights, Screen screen, PopcornPopper popcornPopper) {
    this.amplifier = amplifier;
    this.dvdPlayer = dvdPlayer;
    this.cdPlayer = cdPlayer;
    this.projector = projector;
    this.lights = lights;
    this.screen = screen;
    this.popcornPopper = popcornPopper;
}

public void watchMovie(String movieTitle) {
    popcornPopper.turnOn();
    popcornPopper.pop();
    amplifier.turnOn();
    amplifier.setVolume(10);
    lights.turnOn();
    lights.dim(10);
    screen.up();
    dvdPlayer.turnOn();
    dvdPlayer.play();
}

public void endMovie() {
    dvdPlayer.turnOff();
    screen.down();
    lights.turnOff();
    amplifier.turnOff();
}
}

现在您只需调用 watchMovieendMovie 方法即可,而不是调用所有这些:

public class HomeTheatherFacadeTest {
    public static void main(String[] args){
        Amplifier amplifier = new Amplifier();
        CdPlayer cdPlayer = new CdPlayer();
        DvdPlayer dvdPlayer = new DvdPlayer();
        Lights lights = new Lights();
        PopcornPopper popcornPopper = new PopcornPopper();
        Projector projector = new Projector();
        Screen screen = new Screen();
        
        HomeTheatherFacade homeTheatherFacade = new HomeTheatherFacade(amplifier, dvdPlayer, cdPlayer, projector, lights, screen, popcornPopper);
        homeTheatherFacade.watchMovie("Home Alone");
        homeTheatherFacade.endMovie();
    }
}

所以:

“外观模式为一组
子系统中的接口。 Facade 定义了一个更高级别的接口
使子系统更易于使用。”

I like an example from Eric Freeman, Elisabeth Freeman, Kathy Sierra, Bert Bates - Head First Design Patterns book.
Example:
let's assume you created home theatre and finally you would like to watch a movie. So you have to do:

        Amplifier amplifier = new Amplifier();
        CdPlayer cdPlayer = new CdPlayer();
        DvdPlayer dvdPlayer = new DvdPlayer();
        Lights lights = new Lights();
        PopcornPopper popcornPopper = new PopcornPopper();
        Projector projector = new Projector();
        Screen screen = new Screen();

        popcornPopper.turnOn();
        popcornPopper.pop();
        amplifier.turnOn();
        amplifier.setVolume(10);
        lights.turnOn();
        lights.dim(10);
        screen.up();
        dvdPlayer.turnOn();
        dvdPlayer.play();

what happens when movie is over? You have to do the same but in reverse order so complexity of watch and end movie is becoming very complex. Facade pattern says that you can create a facade and let user just call one method instead of calling all of this.
Let's create facade:

public class HomeTheatherFacade {
    Amplifier amplifier;
    DvdPlayer dvdPlayer;
    CdPlayer cdPlayer;
    Projector projector;
    Lights lights;
    Screen screen;
    PopcornPopper popcornPopper;

    public HomeTheatherFacade(Amplifier amplifier, DvdPlayer dvdPlayer, CdPlayer cdPlayer, Projector projector, Lights lights, Screen screen, PopcornPopper popcornPopper) {
    this.amplifier = amplifier;
    this.dvdPlayer = dvdPlayer;
    this.cdPlayer = cdPlayer;
    this.projector = projector;
    this.lights = lights;
    this.screen = screen;
    this.popcornPopper = popcornPopper;
}

public void watchMovie(String movieTitle) {
    popcornPopper.turnOn();
    popcornPopper.pop();
    amplifier.turnOn();
    amplifier.setVolume(10);
    lights.turnOn();
    lights.dim(10);
    screen.up();
    dvdPlayer.turnOn();
    dvdPlayer.play();
}

public void endMovie() {
    dvdPlayer.turnOff();
    screen.down();
    lights.turnOff();
    amplifier.turnOff();
}
}

and now instead of calling all of this you can just call watchMovie and endMovie methods:

public class HomeTheatherFacadeTest {
    public static void main(String[] args){
        Amplifier amplifier = new Amplifier();
        CdPlayer cdPlayer = new CdPlayer();
        DvdPlayer dvdPlayer = new DvdPlayer();
        Lights lights = new Lights();
        PopcornPopper popcornPopper = new PopcornPopper();
        Projector projector = new Projector();
        Screen screen = new Screen();
        
        HomeTheatherFacade homeTheatherFacade = new HomeTheatherFacade(amplifier, dvdPlayer, cdPlayer, projector, lights, screen, popcornPopper);
        homeTheatherFacade.watchMovie("Home Alone");
        homeTheatherFacade.endMovie();
    }
}

So:

"The Facade Pattern provides a unified interface to a set of
interfaces in a subsytem. Facade defines a higher level interface that
makes the subsystem easier to use."

千仐 2024-10-28 00:08:47

它基本上是单一窗口清除系统。您将其委托给另一个类中的特定方法的任何工作分配给它。

It is basically single window clearance system.You assign any work it will delegate to particular method in another class.

梦晓ヶ微光ヅ倾城 2024-10-28 00:08:47

外观设计模式属于结构设计模式。简而言之,Facade就是外观。这意味着在外观设计模式中我们隐藏了一些东西并只显示客户实际需要的东西。
在下面的博客中阅读更多内容:
http://www.sharepointcafe.net/2017/ 03/facade-design-pattern-in-aspdotnet.html

Facade Design Pattern comes under Structural Design Pattern. In short Facade means the exterior appearance. It means in Facade design pattern we hide something and show only what actually client requires.
Read more at below blog:
http://www.sharepointcafe.net/2017/03/facade-design-pattern-in-aspdotnet.html

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文