package com.modle; /** * 中介者模式 * @author k560 * */ /*需求:产品A要比产品B贵100块,当改A的价格,B的价格也要同步改动,反过来也一样*/ public class Mediator extends AbstractMediator{ private AbstracProduct productA; private AbstracProduct productB; public Mediator(AbstracProduct productA, AbstracProduct productB) { super(); this.productA = productA; this.productB = productB; } @Override public void aAffectB() { this.productB.setPrice(this.productA.getPrice()-100); } @Override public void bAffectA() { this.productA.setPrice(this.productB.getPrice()+100); } public static void main(String[] args) { AbstracProduct pa=new ProductA(); AbstracProduct pb=new ProductB(); AbstractMediator mediator=new Mediator(pa, pb); pa.setPrice(1000,mediator); System.out.println(pb.getPrice()); pb.setPrice(600,mediator); System.out.println(pa.getPrice()); } } /*抽象中介者*/ abstract class AbstractMediator { abstract void aAffectB (); abstract void bAffectA (); } /*抽象产品*/ abstract class AbstracProduct { protected double price; public double getPrice() { return price; } public void setPrice(double price) { this.price = price; } public abstract void setPrice(double price,AbstractMediator mediator); } class ProductA extends AbstracProduct { @Override public void setPrice(double price, AbstractMediator mediator) { this.price=price; mediator.aAffectB(); } } class ProductB extends AbstracProduct { @Override public void setPrice(double price, AbstractMediator mediator) { this.price=price; mediator.bAffectA(); } }
时间: 2024-11-06 03:48:53