情况:
多个类中存在一些相同属性,将其抽取出来
与继承区别?
继承:
继承实在编译时刻静态定义的,较方便复用。但继承对子类暴露了其父类的实现细节,破坏了封装性;子类与父类有着较强的依赖关系,最终限制了复用
组合:
组合是通过获得对其他对象的引用而在运行时刻动态定义的。基于接口进行开发,所以实现上依赖性小
设计模式第二原则:
少用继承,多用组合
关系图:
具体实现
1、实体
contact:
/**
* 共有的联系方式值类
* @author gxq
*
*/
public class Contact {
//定义邮箱、地址、邮箱编号、联系方式
private String email;
private String address;
private String zipCode;
private String contactTel;
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
public String getZipCode() {
return zipCode;
}
public void setZipCode(String zipCode) {
this.zipCode = zipCode;
}
public String getContactTel() {
return contactTel;
}
public void setContactTel(String contactTel) {
this.contactTel = contactTel;
}
}
User:
/**
* 定义用户实体
* @author gxq
*
*/
public class User {
//id、姓名、联系方式
private int id;
private String name;
private Contact userContact;
public Contact getUserContact() {
return userContact;
}
public void setUserContact(Contact userContact) {
this.userContact = userContact;
}
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;
}
}
Employee:
/**
* 定以员工实体
* @author gxq
*
*/
public class Employee {
//id、姓名、联系方式
private int id;
private String name;
private Contact employeeContact;
public Contact getEmployeeContact() {
return employeeContact;
}
public void setEmployeeContact(Contact employeeContact) {
this.employeeContact = employeeContact;
}
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;
}
}
2、映射文件
User:
<component name="userContact">
<property name="email"></property>
<property name="address"></property>
<property name="zipCode"></property>
<property name="contactTel"></property>
</component>
</class>
</hibernate-mapping>
Employee:
<component name="employeeContact">
<property name="email"></property>
<property name="address"></property>
<property name="zipCode"></property>
<property name="contactTel"></property>
</component>
</class>
</hibernate-mapping>
3、配置文件
com.mysql.jdbc.Driver