設計模式之-工廠方法-FactoryMethod

悠悠隱於市發表於2011-04-15

定義一個用於建立物件的介面,讓子類決定例項化哪一個類。FactoryMethod使一個類的例項化延遲到其子類。

 

適用性:

1.當一個類不知道它所必須建立的物件的類的時候。

2.當一個類希望由它的子類來指定它所建立的物件的時候。

3.當類將建立物件的職責委託給多個幫助子類中的某一個,並且你希望將哪一個幫助子類是代理者這一資訊區域性化的時候。
 

 

package pack.java.iworkfactory;

public interface IWork {
	/**
	 * 開始工作方法;
	 */
	public void doWork();
}

 

 

 

package pack.java.iworkfactory;

public interface IWorkFactory {
	/**
	 * 獲取工作;
	 * @return
	 */
	public IWork getWork();
}

 

 

package pack.java.workfactoryimpl;

import pack.java.iworkfactory.IWork;
import pack.java.iworkfactory.IWorkFactory;

public class StudentFactory implements IWorkFactory{

	public IWork getWork() {
		// TODO Auto-generated method stub
		return new StudentWork();
	}

}

 

 

package pack.java.workfactoryimpl;

import pack.java.iworkfactory.IWork;

public class StudentWork implements IWork {

	public void doWork() {
		// TODO Auto-generated method stub
		System.out.println("學生做作業!");
	}
}

 

 

package pack.java.workfactoryimpl;

import pack.java.iworkfactory.IWork;
import pack.java.iworkfactory.IWorkFactory;


public class TeacherFactory implements IWorkFactory{

	public IWork getWork() {
		// TODO Auto-generated method stub
		return new TeacherWork();
	}

}

 

 

package pack.java.workfactoryimpl;

import pack.java.iworkfactory.IWork;

public class TeacherWork implements IWork {

	public void doWork() {
		// TODO Auto-generated method stub
		System.out.println("老師批改作業!");
	}

}

 

 

package pack.java.testfactorymethod;

import pack.java.iworkfactory.IWorkFactory;
import pack.java.workfactoryimpl.StudentFactory;
import pack.java.workfactoryimpl.TeacherFactory;

public class TestFactoryMethod {

	/**
	 * @param args
	 */
	public static void main(String[] args) {
		// TODO Auto-generated method stub
		//學生工廠方法;
		IWorkFactory studentFactory =  new StudentFactory();
		//學生開始工作;
		studentFactory.getWork().doWork();
		
		//老師工廠方法;
		IWorkFactory teacherFactory  = new TeacherFactory();
		//老師開始工作;
		teacherFactory.getWork().doWork();
	}
}

 

 

 

執行結果:

學生做作業!
老師批改作業!

相關文章