设计模式 抽象工厂方法

时间:2022-05-29 07:27:19

先写User 原型类

package User;

public class User {

private int _id;
private String _name;


public int get_id() {
return _id;
}
public void set_id(int _id) {
this._id = _id;
}
public String get_name() {
return _name;
}
public void set_name(String _name) {
this._name = _name;
}


}

在写User访问的具体接口

package User;
public interface IUser {
void Insert(User user);
User GetUser(int id);
}

再写访问User的具体实现

package User;
public class AccessUser implements IUser {

@Override
public void Insert(User user) {
// TODO Auto-generated method stub
System.out.println("在access中给User表添加一条记录");
}

@Override
public User GetUser(int id) {
// TODO Auto-generated method stub
System.out.println("在access中根据ID得到User一条记录");
return null;
}

}
package User;
public class SqlserverUser implements IUser {

public void Insert(User user)
{
System.out.println("再sql server中给User表增加一条记录");
}
public User GetUser(int id)
{
System.out.println("在sql server中根据ID得到User表一条记录");
return null;
}

}

再写工厂方法类

package factory;
import User.IUser;

public interface IFactory {
IUser CreateUser();
}

再写抽象方法的实现

package factory;

import User.IUser;
import User.SqlserverUser;

public class SqlServerFacory implements IFactory {

@Override
public IUser CreateUser() {
// TODO Auto-generated method stub
return new SqlserverUser();
}

}
package factory;

import User.AccessUser;
import User.IUser;

public class AccessFactory implements IFactory {

@Override
public IUser CreateUser() {
// TODO Auto-generated method stub
return new AccessUser();
}

}

再写测试类

import User.IUser;
import User.SqlserverUser;
import User.User;
import factory.IFactory;
import factory.SqlServerFacory;

public class program {

public static void main(String[] args) {
// TODO Auto-generated method stub
User user=new User();
IFactory factory=new SqlServerFacory();
IUser iUser=factory.CreateUser();

iUser.Insert(user);
iUser.GetUser(1);

}

}