wly603

设计模式-----抽象工厂模式

参考:http://blog.csdn.net/ipqxiang/article/details/1955677

       程杰《大话设计模式》清华大学出版社

一、抽象工厂模式

          提供一个创建一系列相关或相互依赖对象的接口,而无需指定它们具体的类。

二、四个重要角色(类)

   抽象工厂、具体工厂、抽象产品、具体产品

三、程序示例

抽象工厂接口
//抽象工厂模式

package com;

//抽象工厂接口:包括2个product: IUser  IDepartment
public interface IFactory 
{
    IUser createUser();
    IDepartment createDepartment();

}

 

具体工厂
//具体工厂: StudentFactory
class StudentFactory implements IFactory
{
    public IUser createUser()
    {
        return new StudentUser();
    }
    
    public IDepartment createDepartment()
    {
        return new StudentDepartment();
    }
}

//具体工厂:  TeacherFactory
class TeacherFactory implements IFactory
{
    public IUser createUser()
    {
        return new TeacherUser();
    }
    
    public IDepartment createDepartment()
    {
        return new TeacherDepartment();
    }
}

 

抽象产品一
//抽象工厂类中的第一个产品

//抽象user接口: 两个方法  设置Name,获取Name
public interface IUser
{
    void setName(String name);

    String getName();
}

 

具体产品一
// 实现user接口: student,teacher
class StudentUser implements IUser 
{
    private String name;

    public void setName(String name) 
    {
        this.name = "Student: " + name;
    }

    public String getName() 
    {
        return name;
    }
}

class TeacherUser implements IUser 
{
    private String name;

    public void setName(String name) 
    {
        this.name = "Teacher: " + name;
    }

    public String getName() 
    {
        return name;
    }
}

 

抽象产品二
//抽象工厂类中的第二个产品

//抽象Department接口: 两个方法  设置Department,获取Department
public interface IDepartment 
{
    void setDepartment(String department);
    
    String getDepartment();
}

 

具体产品二
//实现Department接口: student,teacher
class StudentDepartment implements IDepartment
{
    private String department = null;
    
    public void setDepartment(String department)
    {
        this.department = " Student: "+department;
    }
    
    public String getDepartment()
    {
        return department;
    }
}

class TeacherDepartment implements IDepartment
{
  private String department = null;
    
    public void setDepartment(String department)
    {
        this.department = " Teacher: "+department;
    }
    
    public String getDepartment()
    {
        return department;
    }
}

 

测试程序(客户端)
//客户端测试程序

package com;

public class ClientMain 
{
    public static void main(String[] args)
    {
        String name = "gqy";
        String department ="CSU";
        
        //IFactory student = new StudentFactory();
        IFactory student = new TeacherFactory();
        
        IUser user = student.createUser();
        user.setName(name);
        System.out.println(user.getName());
        
        IDepartment id = student.createDepartment();
        id.setDepartment(department);
        System.out.println(id.getDepartment());        

    }

}

 

posted on 2012-04-11 19:14  wly603  阅读(255)  评论(0编辑  收藏  举报

导航