设计模式入门之访问者模式Visitor

Set集合的配置

数据表的创建:表关系一个员工拥有多个身份

create table EMPLOYEE ( id INT NOT NULL auto_increment, first_name VARCHAR(20) default NULL, last_name VARCHAR(20) default NULL, salary INT default NULL, PRIMARY KEY (id) );
create table CERTIFICATE ( id INT NOT NULL auto_increment, certificate_name VARCHAR(30) default NULL, employee_id INT default NULL, PRIMARY KEY (id) );

创建对应的实体:

package com.study01;

import java.util.Set;

public class Employee {
	private int id;
	private String firstName;
	private String lastName;
	private int salary;
	private Set certificates;

	public Employee() {
	}

	public Employee(String fname, String lname, int salary) {
		this.firstName = fname;
		this.lastName = lname;
		this.salary = salary;
	}

	public int getId() {
		return id;
	}

	public void setId(int id) {
		this.id = id;
	}

	public String getFirstName() {
		return firstName;
	}

	public void setFirstName(String firstName) {
		this.firstName = firstName;
	}

	public String getLastName() {
		return lastName;
	}

	public void setLastName(String lastName) {
		this.lastName = lastName;
	}

	public int getSalary() {
		return salary;
	}

	public void setSalary(int salary) {
		this.salary = salary;
	}

	public Set getCertificates() {
		return certificates;
	}

	public void setCertificates(Set certificates) {
		this.certificates = certificates;
	}

}
package com.study01;

public class Certificate {
	private int id;
	private String name;

	public Certificate() {
	}

	public Certificate(String name) {
		this.name = name;
	}

	public int getId() {
		return id;
	}

	public void setId(int id) {
		this.id = id;
	}

	public String getName() {
		return name;
	}

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

	public boolean equals(Object obj) {
		if (obj == null)
			return false;
		if (!this.getClass().equals(obj.getClass()))
			return false;
		Certificate obj2 = (Certificate) obj;
		//if ((this.id == obj2.getId()) && (this.name.equals(obj2.getName()))) {
		//	return true;
		//}
		if(this.name.equals(obj2.getName())) return true;
		return false;
	}

	public int hashCode() {
		int tmp = 0;
		tmp = (id + name).hashCode();
		return tmp;
	}
}

注意这里对equals和hashCode方法进行了重写。set集合中元素不重复。是否重复,是通过hashCode和equals方法进行比较的。

hibernate主配置文件的配置如下:

<?xml version="1.0" encoding="utf-8"?> <!DOCTYPE hibernate-configuration SYSTEM "http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
	<session-factory>
		<property name="hibernate.dialect"> org.hibernate.dialect.MySQLDialect </property>
		<property name="hibernate.connection.driver_class"> com.mysql.jdbc.Driver </property> <!-- Assume test is the database name -->
		<property name="hibernate.connection.url"> jdbc:mysql://localhost/test </property>
		<property name="hibernate.connection.username"> root </property>
		<property name="hibernate.connection.password"> 253503125 </property> <!-- List of XML mapping files -->
		<mapping resource="com/study01/Employee.hbm.xml" />
		<mapping resource="com/study01/Certificate.hbm.xml" />
	</session-factory>
</hibernate-configuration>

映射文件的配置:

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD//EN" "http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd">
<hibernate-mapping package="com.study01">
	<class name="Employee" table="EMPLOYEE">
		<meta attribute="class-description"> This class contains the employee detail. </meta>
		<id name="id" type="int" column="id">
			<generator class="native" />
		</id>
		<set name="certificates" cascade="all">
			<key column="employee_id" />
			<one-to-many class="Certificate" />
		</set>
		<property name="firstName" column="first_name" type="string" />
		<property name="lastName" column="last_name" type="string" />
		<property name="salary" column="salary" type="int" />
	</class>

</hibernate-mapping>
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD//EN" "http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd">
<hibernate-mapping package="com.study01">

	<class name="Certificate" table="CERTIFICATE">
		<meta attribute="class-description"> This class contains the certificate records. </meta>
		<id name="id" type="int" column="id">
			<generator class="native" />
		</id>
		<property name="name" column="certificate_name" type="string" />
	</class>
</hibernate-mapping>

测试:

package com.study01;

import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Set;

import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.cfg.Configuration;

public class ManageEmployee {
	private static SessionFactory factory;

	public static void main(String[] args) {
		try {
			factory = new Configuration().configure().buildSessionFactory();
		} catch (Throwable ex) {
			System.err.println("Failed to create sessionFactory object." + ex);
			throw new ExceptionInInitializerError(ex);
		}
		ManageEmployee ME = new ManageEmployee();
		HashSet set1 = new HashSet();
		set1.add(new Certificate("MCA"));
		set1.add(new Certificate("MBA"));
		set1.add(new Certificate("PMP"));
		set1.add(new Certificate("MCA"));

		/* Add employee records in the database */
		Integer empID1 = ME.addEmployee("Manoj", "Kumar", 4000, set1); 

		HashSet set2 = new HashSet();
		set2.add(new Certificate("BCA"));
		set2.add(new Certificate("BA"));
		Integer empID2 = ME.addEmployee("Dilip", "Kumar", 3000, set2);

		ME.listEmployees();
		/* Update employee's salary records */
		ME.updateEmployee(empID1, 5000);

		/* Delete an employee from the database */
		ME.deleteEmployee(empID2); /* List down all the employees */
		System.out.println("======================");
		ME.listEmployees();
	} /* Method to add an employee record in the database */

	public Integer addEmployee(String fname, String lname, int salary, Set cert) {
		Session session = factory.openSession();
		Transaction tx = null;
		Integer employeeID = null;
		try {
			tx = session.beginTransaction();
			Employee employee = new Employee(fname, lname, salary);
			employee.setCertificates(cert);
			employeeID = (Integer) session.save(employee);
			tx.commit();
		} catch (HibernateException e) {
			if (tx != null)
				tx.rollback();
			e.printStackTrace();
		} finally {
			session.close();
		}
		return employeeID;
	} /* Method to list all the employees detail */

	public void listEmployees() {
		Session session = factory.openSession();
		Transaction tx = null;
		try {
			tx = session.beginTransaction();
			List employees = session.createQuery("FROM Employee").list();
			for (Iterator iterator1 = employees.iterator(); iterator1.hasNext();) {
				Employee employee = (Employee) iterator1.next();
				System.out.print("First Name: " + employee.getFirstName());
				System.out.print(" Last Name: " + employee.getLastName());
				System.out.println(" Salary: " + employee.getSalary());
				Set certificates = employee.getCertificates();
				for (Iterator iterator2 = certificates.iterator(); iterator2
						.hasNext();) {
					Certificate certName = (Certificate) iterator2.next();
					System.out.println("Certificate: " + certName.getName());
				}
			}
			tx.commit();
		} catch (HibernateException e) {
			if (tx != null)
				tx.rollback();
			e.printStackTrace();
		} finally {
			session.close();
		}
	} /* Method to update salary for an employee */

	public void updateEmployee(Integer EmployeeID, int salary) {
		Session session = factory.openSession();
		Transaction tx = null;
		try {
			tx = session.beginTransaction();
			Employee employee = (Employee) session.get(Employee.class,
					EmployeeID);
			employee.setSalary(salary);
			session.update(employee);
			tx.commit();
		} catch (HibernateException e) {

			if (tx != null)
				tx.rollback();
			e.printStackTrace();
		} finally {
			session.close();
		}
	} /* Method to delete an employee from the records */

	public void deleteEmployee(Integer EmployeeID) {
		Session session = factory.openSession();
		Transaction tx = null;
		try {
			tx = session.beginTransaction();
			Employee employee = (Employee) session.get(Employee.class,
					EmployeeID);
			session.delete(employee);
			tx.commit();
		} catch (HibernateException e) {
			if (tx != null)
				tx.rollback();
			e.printStackTrace();
		} finally {
			session.close();
		}
	}
}

注意在Certificate中添加了两个MCA。运行结果如下:

First Name: Manoj Last Name: Kumar Salary: 4000
Certificate: PMP
Certificate: MCA
Certificate: MBA
First Name: Dilip Last Name: Kumar Salary: 3000
Certificate: BCA
Certificate: BA
======================
First Name: Manoj Last Name: Kumar Salary: 5000
Certificate: PMP
Certificate: MCA
Certificate: MBA

MCA只出现了一次!注意Certificate中hashCode和equals的作用。

设计模式入门之访问者模式Visitor,布布扣,bubuko.com

时间: 2024-08-03 23:34:44

设计模式入门之访问者模式Visitor的相关文章

设计模式 ( 二十 ) 访问者模式Visitor(对象行为型)

1.概述 在软件开发过程中,对于系统中的某些对象,它们存储在同一个集合collection中,且具有不同的类型,而且对于该集合中的对象,可以接受一类称为访问者的对象来访问,而且不同的访问者其访问方式有所不同. 例子1:顾客在超市中将选择的商品,如苹果.图书等放在购物车中,然后到收银员处付款.在购物过程中,顾客需要对这些商品进行访问,以便确认这些商品的质量,之后收银员计算价格时也需要访问购物车内顾客所选择的商品. 此时,购物车作为一个ObjectStructure(对象结构)用于存储各种类型的商品

设计模式之访问者模式(Visitor)摘录

23种GOF设计模式一般分为三大类:创建型模式.结构型模式.行为模式. 创建型模式抽象了实例化过程,它们帮助一个系统独立于如何创建.组合和表示它的那些对象.一个类创建型模式使用继承改变被实例化的类,而一个对象创建型模式将实例化委托给另一个对象.创建型模式有两个不断出现的主旋律.第一,它们都将关于该系统使用哪些具体的类的信息封装起来.第二,它们隐藏了这些类的实例是如何被创建和放在一起的.整个系统关于这些对象所知道的是由抽象类所定义的接口.因此,创建型模式在什么被创建,谁创建它,它是怎样被创建的,以

访问者模式 Visitor 行为型 设计模式(二十七)

访问者模式 Visitor <侠客行>是当代作家金庸创作的长篇武侠小说,新版电视剧<侠客行>中,开篇有一段独白: “茫茫海外,传说有座侠客岛,岛上赏善罚恶二使,每隔十年必到中原武林,向各大门派下发放赏善罚恶令, 强邀掌门人赴岛喝腊八粥,拒接令者,皆造屠戮,无一幸免,接令而去者,杳无音讯,生死未仆,侠客岛之行,已被视为死亡之旅.” 不过话说电视剧,我总是觉得老版的好看. 意图 表示一个作用于某对象结构中的各元素的操作. 它使你可以在不改变各元素类的前提下定义作用于这些元素的新操作.

设计模式学习之访问者模式

访问者模式,是行为型设计模式之一.访问者模式是一种将数据操作与数据结构分离的设计模式,它可以算是 23 中设计模式中最复杂的一个,但它的使用频率并不是很高,大多数情况下,你并不需要使用访问者模式,但是当你一旦需要使用它时,那你就是需要使用它了. 访问者模式的基本想法是,软件系统中拥有一个由许多对象构成的.比较稳定的对象结构,这些对象的类都拥有一个 accept 方法用来接受访问者对象的访问.访问者是一个接口,它拥有一个 visit 方法,这个方法对访问到的对象结构中不同类型的元素做出不同的处理.

设计模式入门之备忘录模式Memento

//备忘录模式定义: //在不破坏封装性的前提下,捕获一个对象的内部状态,并在该对象之外保存这个状态. //这样以后就可以将该对象恢复到原先保存的状态 //实例:测试两种方案,两种方案在第一阶段的过程是相同的,第二阶段是不同的 //实例代码 //备忘录对象的窄接口 public interface FlowAMockMemento { //空的,所谓窄接口,即只是一个标识作用,它的持有者不可以调用任何它的方法 } //测试流程类 public class FlowAMock { private

设计模式入门之桥接模式Bridge

//桥接模式定义:将抽象部分与它的实现部分分离,使得他们都可以独立地变化 //广义来讲,桥接模式非常普遍,面向抽象编程,面向接口编程就可以看作是他的体现 //实例:一个系统,要按照不同的要求发信息(普通,加急,特急),而且还要以不同的方式发送(站内信,Email,短信)等,考虑到其扩展性,用桥接模式再合适不过了 //上代码 //桥接的一半---抽象部分 public abstract class AbstractionMessage { protected MessageImplementor

设计模式入门之迭代器模式Iterator

迭代器模式定义:提供一种方法顺序访问一个聚合对象中的各个元素,而又不需要暴露该对象的内部实现 迭代器模式的结构和说明 Iterator::迭代器接口.定义访问和遍历元素的接口 ConcreteIterator:具体的迭代器实现对象.实现对聚合对象的遍历,并跟踪遍历时的当前位置 Aggregate:聚合对象.定义创建相应迭代器对象的接口 ConcreteAggregate:具体聚合对象.实现创建相应的迭代器对象 实例:一个公司,工资列表是用List实现的,后收购一家公司,工资列表是用Array实现

设计模式入门之模板方法模式TemplateMethod

模板方法模式定义: 定义一个算法的骨架,而将步骤延迟到子类中.这种模式可以使得在不改变算法骨架(模板)的情况下修改每个步骤的具体实现 从功能上来看,这个模式跟生成器模式有些相像,只不过生成器模式定义了创建对象的过程,而模板方法模式定义了算法过程 感觉这个模式要简单很多. 钩子:可以被子类覆盖以实现扩展的方法通常叫做钩子 实例:用户登录过程,分为后台人员登录和用户登录,这是一个非常成型的技术过程,是非常典型的模板方法模式的应用,其中普通用户密码不需要加密,而工作人员的密码需要进行加密比对.上代码

设计模式(17) 访问者模式(VISITOR) C++实现

意图: 表示一个作用于某对象结构的各元素的操作.它使你可以再不改变各元素的类的前提下定义作用于这些元素的新操作. 动机: 之前在学校的最后一个小项目就是做一个编译器,当时使用的就是访问者模式. 在静态分析阶段,将源程序表示为一个抽象语法树,编译器需要在抽象语法树的基础上实施某些操作以进行静态语义分析.可能需要定义许多操作以进行类型检查.代码优化.流程分析.检查变量是否在使用前被赋值,等等. 这个需求的特点是:要求对不同的节点进行不同的处理. 常规设计方法:不同的节点封装不同的操作. 缺点是,节点