使用匿名内部类完成抽象工厂模式
写这篇文章 是我对匿名类以及抽象工厂的一个理解...觉得有所启发就写了下来..希望大家能够一起学习...
抽象工厂类
package com.chusiyou.factory;
public abstract class Factory {
public abstract UserDao getUserDao();
public abstract PersonDao getPersonDao();
//获得工厂实例的一个方法
public static Factory getFactory(String dataBaseName)
{
//针对数据库不同而采取不同的JDBC操作
if(dataBaseName.equals("mysql"))
{
return new Factory()
{
public PersonDao getPersonDao() {
// TODO Auto-generated method stub
return new PersonDao()
{
//JDBC代码......
public boolean addPerson(Person person) {
// TODO Auto-generated method stub
return false;
}
public boolean deletePerson(Person person) {
// TODO Auto-generated method stub
return false;
}
};
}
public UserDao getUserDao() {
// TODO Auto-generated method stub
return new UserDao()
{
public boolean addUser(User user) {
// TODO Auto-generated method stub
return true;
}
public boolean deleteUser(User user) {
// TODO Auto-generated method stub
return false;
}
};
}
};
}else if(dataBaseName.equals("orcale"))
{
return new Factory()
{
public PersonDao getPersonDao() {
// TODO Auto-generated method stub
return new PersonDao()
{
public boolean addPerson(Person person) {
// TODO Auto-generated method stub
return false;
}
public boolean deletePerson(Person person) {
// TODO Auto-generated method stub
return false;
}
};
}
public UserDao getUserDao() {
// TODO Auto-generated method stub
return new UserDao()
{
public boolean addUser(User user) {
// TODO Auto-generated method stub
return false;
}
public boolean deleteUser(User user) {
// TODO Auto-generated method stub
return false;
}
};
}
};
}
return null;
}
}
一些别的业务接口 和实体类
package com.chusiyou.factory;
//定义对数据库访问的业务接口
public interface PersonDao {
//删除的操作
public boolean deletePerson(Person person);
//增加的操作
public boolean addPerson(Person person);
}
package com.chusiyou.factory;
//定义对数据库访问的业务接口
public interface UserDao {
public boolean deleteUser(User user);
public boolean addUser(User user);
}
package com.chusiyou.factory;
//实体类
public class Person {
}
package com.chusiyou.factory;
//实体类
public class User {
}
测试类
package com.chusiyou.factory;
public class FactoryTest {
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
User user=new User();
if(Factory.getFactory("Access").getUserDao().addUser(user))
{
System.out.println("增加成功");
}else
{
System.out.println("增加失败");
}
}
}