《大话设计模式》第十五章
package ch15;
public class User {
private int id;
private String name;
public User(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;
}
}
package ch15;
public interface IUser {
void insert(User user);
User getUser(int id);
}
package ch15;
public class AccessUser implements IUser {
public void insert(User user) {
System.out.println("在Access里插入" + user.getName());
}
public User getUser(int id) {
System.out.println("在Access里根据ID得到User");
return null;
}
}
package ch15;
public class SqlserverUser implements IUser {
public void insert(User user) {
System.out.println("在SQL Server里插入" + user.getName());
}
public User getUser(int id) {
System.out.println("在SQL Server里根据ID得到User");
return null;
}
}
package ch15;
public interface IFactory {
IUser createUser();
}
package ch15;
public class AccessFactory implements IFactory {
public IUser createUser() {
return new AccessUser();
}
}
package ch15;
public class SqlserverFactory implements IFactory {
public IUser createUser() {
return new SqlserverUser();
}
}
package ch15;
/**
* 抽象工厂模式
* @author Administrator
*
*/
public class Client {
/**
* @param args
*/
public static void main(String[] args) {
User user = new User("X");
IFactory factory = new SqlserverFactory();
IUser iu = factory.createUser();
iu.insert(user);
iu.getUser(0);
}
}
抽象工厂模式和工厂方法模式很像,那么有什么区别吗?
工厂方法,返回一个具体的类型,比如Integer.valueOf,返回的是Integer的实例,而且Integer不是抽象类,是可以实例化的;
抽象工厂方法,返回的可能是任何的类型,Calendar.getInstance,返回的可能是BuddhistCalendar,也可能是JapaneseImperialCalendar,也可能是GregorianCalendar,而且Calendar是抽象类,不能实例化。