行为设计模式:中介者
                                                            生活随笔
收集整理的這篇文章主要介紹了
                                行为设计模式:中介者
小編覺得挺不錯的,現(xiàn)在分享給大家,幫大家做個參考.                        
                                以前我們看過迭代器模式。
中介者模式在實現(xiàn)目標上有很大的不同。 它是行為模式之一,其目的是改變對象之間的通信方式。 中介器將代替對象之間的直接通信,而不是直接相互通信。
例如,想象一下金融交易的場景。 您確實想交易和購買,但您不直接從提出報價的那一方購買。 相反,交換在中間,以便您進行交易。
人們想買賣。 交換將對此提供便利。 您有訂單對象。
package com.gkatzioura.design.behavioural.mediator;public class Order {private String stock;private Integer quantity;private Double price;public String getStock() {return stock;}public void setStock(String stock) {this.stock = stock;}public Integer getQuantity() {return quantity;}public void setQuantity(Integer quantity) {this.quantity = quantity;}public Double getPrice() {return price;}public void setPrice(Double price) {this.price = price;}}下一個對象是出售股票的金融實體。
package com.gkatzioura.design.behavioural.mediator;public class FinancialEntity {public boolean sell(Order order) {/*** Supposing the sale was successful return true*/return true;}}然后我們創(chuàng)建交換對象。 我們不會進一步探討傭金問題,但可以想象事情會變得更加復雜。 交流實際上是我們的調(diào)解人。
package com.gkatzioura.design.behavioural.mediator;public class Exchange {private FinancialEntity financialEntity;public Exchange(FinancialEntity financialEntity) {this.financialEntity = financialEntity;}public void serve(Order order) {/*** Choose the financial entity suitable for the order*/financialEntity.sell(order);}}最后一步是創(chuàng)建交易者對象。
package com.gkatzioura.design.behavioural.mediator;public class Trader {private Exchange exchange;public Trader(Exchange exchange) {this.exchange = exchange;}public void buy(String stock,Integer quantity,Double price) {Order order = new Order();order.setStock(stock);order.setQuantity(quantity);order.setPrice(price);exchange.serve(order);}}如您所見,交易者對象沒有直接與提供股票的金融實體進行交互。
讓我們將它們放到一個主類中。
package com.gkatzioura.design.behavioural.mediator;public class Mediator {public static void main(String[] args) {final FinancialEntity financialEntity = new FinancialEntity();final Exchange exchange = new Exchange(financialEntity);Trader trader = new Trader(exchange);trader.buy("stock_a",2,32.2d);} }就是這樣,您僅將調(diào)解器模式用于交換應用程序! 您也可以在github上找到源代碼。
翻譯自: https://www.javacodegeeks.com/2018/11/behavioural-design-patterns-mediator.html
總結
以上是生活随笔為你收集整理的行为设计模式:中介者的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
 
                            
                        - 上一篇: 腾讯企业邮箱pop3设置(QQ邮箱pop
- 下一篇: 安卓卸载预装软件(安卓卸载预装)
