中介者(Mediator)模式实例应用——房屋租赁(java)

中介者(Mediator)模式实例应用——房屋租赁(java),第1张

目录

中介者模式介绍

中介者模式中的角色

UML类图

中介者模式实例(房屋租赁)

情景假设

案例分析

程序结构分析

程序代码

运行结果:

总结

优缺点

优点

缺点

应用场景


中介者模式介绍

        中介者模式(Mediator),用一个中介对象来封装一系列的对象交互。中介者使各对象不需要显示的相互引用,从而使其耦合松散,而且可以独立地改变它们之间的交互。中介者模式是对象行为型模式的一种,旨在处理类或对象如何交互及如何分配职责。当一个系统对象很多,且之间关联关系很复杂,交叉引用容易产生混乱时,就可能适用中介者模式。

        传统的中介者模式是迪米特法则的典型应用,做到了每个对象了解最少的内容,类之间各司其职,降低了对象之间的耦合性,使得对象易于独立地被复用。同时中介者模式将对象间的一对多关联转变为一对一的关联,提高系统的灵活性,使得系统易于维护和扩展,这对大型程序来说是非常有益的。

            

中介者模式中的角色

中介者模式的结构中包括四种角色:

中介者(Mediator):中介者是一个接口,该接口定义了用于同事(Colleague)对象之间进行通信的方法。

具体中介者(ConcreteMediator):具体中介者是实现中介者接口的类。具体中介者需要包含所有具体同事(ConcreteColleague)的引用,并通过实现中介者接口中的方法来满足具体同事之间的通信。

同事(Colleague):一个接口,规定了具体同事需要实现的方法。

具体同事(ConcreteColleague):实现同事接口的类。具体同事需要包含具体中介者的引用,一个具体同事和其他具体同事交互时,只需将自己的请求通知给它所包含的具体终结者即可。

UML类图

中介者模式实例(房屋租赁) 情景假设

        某中介公司欲为租户和房东打造一个平台,二者可在此平台注册自己的信息,此平台会根据用户所填写的信息为其匹配合适的租户或房东。

案例分析 程序结构分析

        首先,定义一个中介公司(Mediator)类(此项目中没有定义中介者接口,把具体中介者对象实现成为单例,简化了中介者模式),它包含了客户注册方法(register(Colleague colleague)),寻找租客方法(findRenter(Landlord landlord))和寻找房东方法(findLandlord(Renter renter))。同时它也包含了保存客户信息的 List 对象,并实现了其定义的方法。

        然后,定义一个客户(Colleague)类,它是抽象同事类,其中包含了中介者的对象和客户注册方法(register())的接口。

        最后,定义租户(Renter)类和房东(Landlord)类,它们是具体同事类,是客户(Colleague)类的子类,它们实现了父类中的抽象方法同时也实现了各自定义的方法(findLandlord())和(findRenter())。其结构图如下图所示:

程序代码

项目结构:

抽象中介者角色和具体中介者角色(简单单例中介者) :

package mediator;

import java.util.ArrayList;
import java.util.List;

public class Mediator {
	private List landlords=new ArrayList<>();//房东
	private List renters=new ArrayList<>();//租客
	
	Mediator(){}
	
	//注册租户和房东
	public void register(Colleague colleague) {
		if(colleague instanceof Landlord) {
			landlords.add((Landlord) colleague);
		}else {
			renters.add((Renter) colleague);
		}
	}
	
	//寻找合适的租户
	public List findRenter(Landlord landlord) {	
		Double requestPrice1;
		Double requestPrice2;
		Double requestArea1;
		Double requestArea2;
		List renterList=new ArrayList<>();
		for(Renter renter:renters) {
			requestPrice1=renter.getRequestPrice1();
			requestPrice2=renter.getRequestPrice2();
			requestArea1=renter.getRequestArea1();
			requestArea2=renter.getRequestArea2();
			if(landlord.getPrice()>=requestPrice1 && landlord.getPrice()<=requestPrice2
					&& landlord.getArea()>=requestArea1 && landlord.getArea()<=requestArea2)
				renterList.add(renter);
		}
		if(renterList.isEmpty())
			return null;
		return renterList;
	}
	
	//寻找合适的房东
	public List findLandlord(Renter renter) {
		Double price;
		Double area;
		List landlordList=new ArrayList<>();
		for(Landlord landlord:landlords) {
			price=landlord.getPrice();
			area=landlord.getArea();
			if(renter.getRequestArea1()<=area && renter.getRequestArea2()>=area
					&& renter.getRequestPrice1()>=price && renter.getRequestPrice2()<=price)
				landlordList.add(landlord);
		}
		if(landlordList.isEmpty())
			return null;
		return landlordList;
	}
}

抽象同事类:

package mediator;

public interface Colleague {
	public void register();
}

具体同事类1(租户类):

package mediator;

import java.util.List;

public class Renter implements Colleague{
	private String name;
	private String phoneNumber;
	private double requestPrice1;
	private double requestPrice2;
	private double requestArea1;
	private double requestArea2;
	
	Mediator mediator;
	
	Renter(){}
	
	Renter(String name,String phoneNumber,double requestPrice1,double requestPrice2,
			double requestArea1,double requestArea2){
		this.name=name;
		this.phoneNumber=phoneNumber;
		this.requestArea1=requestArea1;
		this.requestArea2=requestArea2;
		this.requestPrice1=requestPrice1;
		this.requestPrice2=requestPrice2;
	}
	
	public void register() {
		mediator.register(this);
	}
	
	public List findLandlord() {
		return mediator.findLandlord(this);
	}

	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}

	public String getPhoneNumber() {
		return phoneNumber;
	}

	public void setPhoneNumber(String phoneNumber) {
		this.phoneNumber = phoneNumber;
	}

	public double getRequestPrice1() {
		return requestPrice1;
	}

	public void setRequestPrice1(double requestPrice1) {
		this.requestPrice1 = requestPrice1;
	}

	public double getRequestPrice2() {
		return requestPrice2;
	}

	public void setRequestPrice2(double requestPrice2) {
		this.requestPrice2 = requestPrice2;
	}

	public double getRequestArea1() {
		return requestArea1;
	}

	public void setRequestArea1(double requestArea1) {
		this.requestArea1 = requestArea1;
	}

	public double getRequestArea2() {
		return requestArea2;
	}

	public void setRequestArea2(double requestArea2) {
		this.requestArea2 = requestArea2;
	}

	public Mediator getMediator() {
		return mediator;
	}

	public void setMediator(Mediator mediator) {
		this.mediator = mediator;
	}
}

具体同事类2(房东类):

package mediator;

import java.util.List;

public class Landlord implements Colleague{
	private String name;
	private String phoneNumber;
	private String address;
	private double price;
	private double area;
	
	Mediator mediator;
	
	Landlord(){}
	
	Landlord(String name,String phoneNumber,String address,double price,double area) {
		this.name=name;
		this.phoneNumber=phoneNumber;
		this.address=address;
		this.price=price;
		this.area=area;
	}
	
	public List findRenter() {
		return mediator.findRenter(this);
	}
	
	public void register() {
		mediator.register(this);
	}

	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}

	public String getPhoneNumber() {
		return phoneNumber;
	}

	public void setPhoneNumber(String phoneNumber) {
		this.phoneNumber = phoneNumber;
	}

	public String getAddress() {
		return address;
	}

	public void setAddress(String address) {
		this.address = address;
	}

	public double getPrice() {
		return price;
	}

	public void setPrice(double price) {
		this.price = price;
	}

	public double getArea() {
		return area;
	}

	public void setArea(double area) {
		this.area = area;
	}

	public Mediator getMediator() {
		return mediator;
	}

	public void setMediator(Mediator mediator) {
		this.mediator = mediator;
	}
	
}

主函数(应用实例):

package mediator;

import java.awt.Color;
import java.awt.Container;
import java.awt.Dimension;
import java.awt.Font;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.util.List;
import java.util.Vector;

import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JDialog;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JMenuItem;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.JTextField;
import javax.swing.SwingConstants;

public class Application{
	
	static Mediator mediator=new Mediator();
	
	public static void main(String[] args) throws Exception {
		read();
		firstPage();
	}	
	
	private static void firstPage() throws Exception{
		
		//设置窗体大小和标题
		JFrame jf=new JFrame("房屋租赁中介");
		jf.setSize(300,320);
		jf.setLocationRelativeTo(null);//窗体居中显示
		
		//容器
		JPanel panel=new JPanel();
		panel.setLayout(null);
		
		//按钮和图片
		JButton jbutton1=new JButton("租赁房屋");
		JButton jbutton2=new JButton("出租房屋");
		panel.add(jbutton1);
		panel.add(jbutton2);
		jbutton1.setSize(100,30);
		jbutton2.setSize(100,30);
		jbutton1.setLocation(100,200);
		jbutton2.setLocation(100,240);
		
		JLabel picture=new JLabel(new ImageIcon("src/租房.png"));
		picture.setBounds(50,0,200,200);
		panel.add(picture);
		
		//添加按钮事件
		jbutton1.addActionListener(new ActionListener() {
			@Override
			public void actionPerformed(ActionEvent e) {
				// TODO Auto-generated method stub
				JDialog dialog = new JDialog();
				dialog.setTitle("填写出租信息");
				dialog.setSize(400,380);
				dialog.setLocationRelativeTo(null);
				
				JPanel jp=new JPanel();
				jp.setLayout(null);
				
				//填写信息
				JLabel name=new JLabel("姓名:");
				name.setFont(new Font("微软雅黑", Font.PLAIN, 18));
				name.setBounds(40, 20, 100, 40);
				JLabel number=new JLabel("联系电话:");
				number.setFont(new Font("微软雅黑", Font.PLAIN, 18));
				number.setBounds(40, 70, 100, 40);
				JLabel address=new JLabel("房屋位置:");
				address.setFont(new Font("微软雅黑", Font.PLAIN, 18));
				address.setBounds(40, 120, 100, 40);
				JLabel area=new JLabel("房屋面积:");
				area.setFont(new Font("微软雅黑", Font.PLAIN, 18));
				area.setBounds(40, 170, 100, 40);
				JLabel price=new JLabel("房屋价格:");
				price.setFont(new Font("微软雅黑", Font.PLAIN, 18));
				price.setBounds(40, 220, 100, 40);
				
				JTextField name1=new JTextField();
				name1.setBounds(150, 20, 200, 40);
				JTextField number1=new JTextField();
				number1.setBounds(150, 70, 200, 40);
				JTextField address1=new JTextField();
				address1.setBounds(150, 120, 200, 40);
				JTextField area1=new JTextField();
				area1.setBounds(150, 170, 200, 40);
				JTextField price1=new JTextField();
				price1.setBounds(150, 220, 200, 40);
				
				jp.add(name);
				jp.add(number);
				jp.add(address);
				jp.add(area);
				jp.add(price);
				jp.add(name1);
				jp.add(number1);
				jp.add(address1);
				jp.add(area1);
				jp.add(price1);
				
				//按钮
				JButton jbutton3=new JButton("出租房屋");
				//JButton jbutton4=new JButton("注册登记");
				jp.add(jbutton3);
				//jp.add(jbutton4);
				jbutton3.setSize(100,30);
				//jbutton4.setSize(100,30);
				jbutton3.setLocation(150,300);
				//jbutton4.setLocation(150,340);
				
				//添加按钮事件
				jbutton3.addActionListener(new ActionListener() {
					
					@Override
					public void actionPerformed(ActionEvent e) {
						// TODO Auto-generated method stub
						Landlord ll=new Landlord(name1.getText(), number1.getText(), address1.getText(), Double.parseDouble(price1.getText()), Double.parseDouble(area1.getText()));
						ll.setMediator(mediator);
						List renters=ll.findRenter();
						
						if(renters==null) {
							JDialog dialog1 = new JDialog();
							dialog1.setTitle("无符合租户信息");
							dialog1.setSize(200,220);
							dialog1.setLocationRelativeTo(null);
							
							JLabel jl=new JLabel("无符合条件租户");
							jl.setFont(new Font("微软雅黑", Font.BOLD, 15));
							dialog1.add(jl);
							dialog1.setVisible(true);
							
						}else {
							JDialog dialog1 = new JDialog();
							dialog1.setTitle("符合租户信息");
							dialog1.setSize(800,420);
							dialog1.setLocationRelativeTo(null);
							
							//表格
							JTable jt;
							JScrollPane jsp;
							Vector columnName = new Vector();
							//设置列名
							columnName.add("姓名");
							columnName.add("联系电话");
							columnName.add("最低价");
							columnName.add("最高价");
							columnName.add("最小面积");
							columnName.add("最大面积");
							Vector rowData = new Vector();
							for(Renter renter:renters) {
								Vector line=new Vector();
								line.add(renter.getName());
								line.add(renter.getPhoneNumber());
								line.add(renter.getRequestPrice1());
								line.add(renter.getRequestPrice2());
								line.add(renter.getRequestArea1());
								line.add(renter.getRequestArea2());
								rowData.add(line);
							}
							jt=new JTable(rowData,columnName);
							jsp=new JScrollPane(jt);
							jt.getTableHeader().setPreferredSize(new Dimension(1, 40));
							jt.getTableHeader().setFont(new Font("楷体", Font.PLAIN, 21));
							jt.setRowHeight(60);
							jt.setFont(new Font("楷体", Font.PLAIN, 17));
							
							dialog1.add(jsp);
							dialog1.setVisible(true);
						}
						
					}
				});
				
				dialog.add(jp);
				dialog.setVisible(true);
			}
		});
		
		//添加按钮事件
		jbutton2.addActionListener(new ActionListener() {
			@Override
			public void actionPerformed(ActionEvent e) {
				// TODO Auto-generated method stub
				JDialog dialog = new JDialog();
				dialog.setTitle("填写租赁信息");
				dialog.setSize(400,420);
				dialog.setLocationRelativeTo(null);
						
				JPanel jp=new JPanel();
				jp.setLayout(null);
						
				//填写信息
				JLabel name=new JLabel("姓名:");
				name.setFont(new Font("微软雅黑", Font.PLAIN, 18));
				name.setBounds(40, 20, 100, 40);
				JLabel number=new JLabel("联系电话:");
				number.setFont(new Font("微软雅黑", Font.PLAIN, 18));
				number.setBounds(40, 70, 100, 40);
				JLabel minprice=new JLabel("最低价:");
				minprice.setFont(new Font("微软雅黑", Font.PLAIN, 18));
				minprice.setBounds(40, 120, 100, 40);
				JLabel maxprice=new JLabel("最高价:");
				maxprice.setFont(new Font("微软雅黑", Font.PLAIN, 18));
				maxprice.setBounds(40, 170, 100, 40);
				JLabel minarea=new JLabel("最小面积:");
				minarea.setFont(new Font("微软雅黑", Font.PLAIN, 18));
				minarea.setBounds(40, 220, 100, 40);
				JLabel maxarea=new JLabel("最大面积:");
				maxarea.setFont(new Font("微软雅黑", Font.PLAIN, 18));
				maxarea.setBounds(40, 270, 100, 40);
						
				JTextField name1=new JTextField();
				name1.setBounds(150, 20, 200, 40);
				JTextField number1=new JTextField();
				number1.setBounds(150, 70, 200, 40);
				JTextField minprice1=new JTextField();
				minprice1.setBounds(150, 120, 200, 40);
				JTextField maxprice1=new JTextField();
				maxprice1.setBounds(150, 170, 200, 40);
				JTextField minarea1=new JTextField();
				minarea1.setBounds(150, 220, 200, 40);
				JTextField maxarea1=new JTextField();
				maxarea1.setBounds(150, 270, 200, 40);
						
				jp.add(name);
				jp.add(number);
				jp.add(minprice);
				jp.add(maxprice);
				jp.add(minarea);
				jp.add(maxarea);
				jp.add(name1);
				jp.add(number1);
				jp.add(minprice1);
				jp.add(maxprice1);
				jp.add(minarea1);
				jp.add(maxarea1);
						
				//按钮
				JButton jbutton3=new JButton("租赁房屋");
				//JButton jbutton4=new JButton("注册登记");
				jp.add(jbutton3);
				//jp.add(jbutton4);
				jbutton3.setSize(100,30);
				//jbutton4.setSize(100,30);
				jbutton3.setLocation(150,340);
				//jbutton4.setLocation(150,380);
						
				//添加按钮事件
				jbutton3.addActionListener(new ActionListener() {
							
					@Override
					public void actionPerformed(ActionEvent e) {
						// TODO Auto-generated method stub
						Renter r=new Renter(name1.getText(), number1.getText(), Double.parseDouble(minprice1.getText()), Double.parseDouble(maxprice1.getText()),Double.parseDouble(minarea1.getText()), Double.parseDouble(maxarea1.getText()));
						r.setMediator(mediator);
						List landlords=r.findLandlord();
								
						if(landlords==null) {
							JDialog dialog1 = new JDialog();
							dialog1.setTitle("无符合房东信息");
							dialog1.setSize(200,220);
							dialog1.setLocationRelativeTo(null);
									
							JLabel jl=new JLabel("无符合条件房东");
							jl.setFont(new Font("微软雅黑", Font.BOLD, 15));
							dialog1.add(jl);
							dialog1.setVisible(true);
									
						}else {
							JDialog dialog1 = new JDialog();
							dialog1.setTitle("符合房东信息");
							dialog1.setSize(800,420);
							dialog1.setLocationRelativeTo(null);
									
							//表格
							JTable jt;
							JScrollPane jsp;
							Vector columnName = new Vector();
							//设置列名
							columnName.add("姓名");
							columnName.add("联系电话");
							columnName.add("地址");
							columnName.add("价格");
							columnName.add("面积");
							Vector rowData = new Vector();
							for(Landlord landlord:landlords) {
								Vector line=new Vector();
								line.add(landlord.getName());
								line.add(landlord.getPhoneNumber());
								line.add(landlord.getAddress());
								line.add(landlord.getPrice());
								line.add(landlord.getArea());
								rowData.add(line);
							}
							jt=new JTable(rowData,columnName);
							jsp=new JScrollPane(jt);
							jt.getTableHeader().setPreferredSize(new Dimension(1, 40));
							jt.getTableHeader().setFont(new Font("楷体", Font.PLAIN, 21));
							jt.setRowHeight(60);
							jt.setFont(new Font("楷体", Font.PLAIN, 17));
								
								dialog1.add(jsp);
								dialog1.setVisible(true);
							}
								
						}
					});
						
					dialog.add(jp);
					dialog.setVisible(true);
					}
				});
		
		//设置窗体可见
		jf.add(panel);
		jf.setVisible(true);
	}
	
	//文件读取
	public static void read() throws Exception {
		StringBuffer sb=new StringBuffer();
		BufferedReader br=new BufferedReader(new FileReader("src/房东.txt"));
		String data=br.readLine();
		while(data!=null) {
			String[] string=data.split("\\s+");
			Landlord landlord=new Landlord(string[0],string[1],string[2],Double.parseDouble(string[3]),Double.parseDouble(string[4]));
			mediator.register(landlord);
			data=br.readLine();
		}
		br.close();
		br=new BufferedReader(new FileReader("src/租户.txt"));
		data=br.readLine();
		while(data!=null) {
			String[] string=data.split("\\s+");
			Renter renter=new Renter(string[0],string[1],Double.parseDouble(string[2]),Double.parseDouble(string[3]),Double.parseDouble(string[4]),Double.parseDouble(string[5]));
			mediator.register(renter);
			data=br.readLine();
		}
		br.close();
	}
}

其他文件:

房东.txt:

张三     11111111111       中央花园2幢13号      3000       100
李四     22222222222       中央花园5幢24号      2000       70
王五     33333333333       留和路18号           1500       50
王三     44444444444       翻斗花园3幢6号       1800       75
孙五     55555555555       翻斗花园5幢3号       2500       85
徐七     66666666666       丰泽小区8幢15号      1200       50

租户.txt:

小明     99999999999    1250    1750   30   70
小红     88888888888    1500    2500   50   100
小刚     77777777777    2000    3500   100   150
小孙     98765432101    2500    3000   80    120
小孔     12345678909    1750    3000   60    120
小张     14725836909    2200    2800   80    115

租房.png:

运行结果

房东出租房屋:

首先填写信息:

系统查询匹配的租户,若成功则显示所有符合的租户的信息:

否则显示:

租户租赁房屋:

首先填写信息:

系统查询匹配房东,若成功则显示所有符合的房东的信息:

否则显示:

总结 优缺点 优点
  1. 简化了对象之间的交互,它用中介者和同事的一对多交互替代了原来同事之间的多对多交互
  2. 适当地使用中介者模式可以避免同事类之间的过度耦合,使得各同事类之间可以相对独立地使用。
  3. 可以减少大量同事子类的生成,改变同事行为只需要生成新的中介者子类即可。
  4. 它将对象的行为和协作进行抽象,能够比较灵活的处理对象间的相互作用。
缺点

        中介者模式虽然好,但过度使用可能使中介者逻辑非常复杂。它使控制集中化,中介者模式将交互的复杂性变为中介者的复杂性。因为中介者封装了协议,它可能比每个 Colleague 都复杂,它将原本多个对象直接的相互依赖变成了中介者和多个同事类的依赖关系。当同事类越多时,中介者就会越臃肿,变得复杂且难以维护。这可能使得中介者自身成为一个难于维护的庞然大物。

应用场景

        中介者模式很容易实现,但是也容易误用,不要着急使用,先要思考你的设计是否合理。
当对象之间的交互变多时,为了防止一个类会涉及修改其他类的行为,可以使用中介者模式,将系统从网状结构变为以中介者为中心的星型结构。

  1. 系统中对象之间存在复杂的引用关系,产生的相互依赖关系结构混乱且难以理解。
  2. 一个对象由于引用了其他很多对象并且直接和这些对象通信,导致难以复用该对象。
  3. 想通过一个中间类来封装多个类中的行为,而又不想生成太多的子类。

欢迎分享,转载请注明来源:内存溢出

原文地址: https://outofmemory.cn/langs/876671.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-05-13
下一篇 2022-05-13

发表评论

登录后才能评论

评论列表(0条)

保存