工厂方法模式是什么java设计模式介绍使用方法步骤,工厂方法模式是什么?java设计模式介绍。Factory Method(也就是工厂方法)模式的主要目的是用在创建对象的接口上面,而且还可以控制对哪个对象进行实例化。在java工厂方法模式中,工厂方法用户不用知道该实例化什么类,其用意主是为所实例化的多个类定义公共接口,而服务提供者来确定将要实例化上述类中的哪一个类而不是由客户代码。
java工厂方法模式通常会出现在客户代码里面,特别是发生在客户代码不必要了解具体实例化哪一个类的情况下。使用工厂方法模式的典型范例是Collection框架中的迭代器。Iterator模式给了顺序访问集合中元素的一种方式,然而创建迭代器常常要使用Factory Method模式。Java 1.2引入了Collection接口,另外还包括iterator()方法,所有集合都应该实现这个方法,iterator()使得调用者不必了解需要实例化哪个类。
Java Collection框架中,抽象类AbstractList<E>含有以下方法:
- public Interator<E> iterator() {
- return new Itr();
- }
其中,Itr定义为AbstractList<E>的一个内部私有类,代码示例如下:
- private class Itr implements Iterator<E> {
- /**
- * Index of element to be returned by subsequent call to next.
- */
- int cursor = 0;
- ……
- }
iterator()方法创建的对象顺序包括了集合中的各个元素,迭代器的具体使用方法能够参考以下代码:
- import java.util.ArrayList;
- import java.util.Iterator;
- import java.util.List;
- public class FactoryMethodIterator {
- /**
- * @param args
- */
- public static void main(String[] args) {
- List<String> list = new ArrayList<String>();
- list.add(“string one”);
- list.add(“string two”);
- list.add(“string three”);
- Iterator<String> iterator = list.iterator();
- while(iterator.hasNext()) {
- System.out.print(iterator.next() + ” ”);
- }
- }
- }
- //其输出结果为
- string one string two string three
在常见的Spring Web架构中,org.springframework.beans.factory.BeanFactory接口提供Object getBean(String name)及其重载方法,能够将其看作Factory Method模式的一个典型应用。
Factory Method工厂方法模式的简单实例步骤代码如下:
(1)定义多个类的公共接口Store
- package codolio.test;
- public interface Store {
- void store(String msg);
- }
(2)实现具体的工厂方法
- package codolio.test;
- public class StoreFactory {
- public Store getStore(String location) {
- Store store = null;
- if (location.equalsIgnoreCase(“file”)) {
- store = new FileStore();
- }
- else if (location.equalsIgnoreCase(“database”)) {
- store = new DatabaseStore();
- }
- return store;
- }
- private class FileStore implements Store {
- public void store(String msg) {
- //store the data in the file
- System.out.println(“The message ” + msg + ” has been stored – [File]“);
- }
- }
- private class DatabaseStore implements Store {
- public void store(String msg) {
- //store the data in the database
- System.out.println(“The message ” + msg + ” has been stored – [database]“);
- }
- }
- }
(3)测试类及输出结果
- package codolio.test;
- /**
- * @author codolio
- *
- */
- public class FactoryMethodTest {
- /**
- * @param args
- */
- public static void main(String[] args) {
- StoreFactory storeFactory = new StoreFactory();
- Store store = storeFactory.getStore(“file”);
- store.store(“This is my message”);
- store = storeFactory.getStore(“database”);
- store.store(“This is my message”);
- }
- }
- //输出结果
- The message This is my message has been stored – [File]
- The message This is my message has been stored – [database]
在上述示例中,FileStore和DatabaseStore并不是一定要实现为StoreFactory的内部私有类。而且,在工厂方法模式里面,对公共接口的要求并非如此严格。就如,在Spring架构中,通过Spring IoC容器返回的Java对象间彼此关系通常都显得很松散,而且没有实现共同的接口。