`

static factory method

 
阅读更多
package ycl.learn.effective.java;

import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;

/**
 * java.long.Boolean
 *  
     * The <code>Boolean</code> object corresponding to the primitive 
     * value <code>true</code>. 
    public static final Boolean TRUE = new Boolean(true);
  
     * The <code>Boolean</code> object corresponding to the primitive 
     * value <code>false</code>. 
    public static final Boolean FALSE = new Boolean(false);
    
 	 * Returns a <tt>Boolean</tt> instance representing the specified
     * <tt>boolean</tt> value.  If the specified <tt>boolean</tt> value
     * is <tt>true</tt>, this method returns <tt>Boolean.TRUE</tt>;
     * if it is <tt>false</tt>, this method returns <tt>Boolean.FALSE</tt>.
     * If a new <tt>Boolean</tt> instance is not required, this method
     * should generally be used in preference to the constructor
     * {@link #Boolean(boolean)}, as this method is likely to yield
     * significantly better space and time performance.
    public static Boolean valueOf(boolean b) {
        return (b ? TRUE : FALSE);
    }
 * 
 * Enum
 * 
 * public enum UserEnum {
		ACTION("ACTION"),FIRST_NAME("FIRST NAME"),LAST_NAME("LAST NAME"),E_MAIL("E-MAIL"),PHONE("PHONE");
		
		private String name=null; 
		private UserEnum(String name){
			this.name = name;
		}
		public String getName(){
			return name;
		} 
	}
 * jad class File:
 * 
 * public final class UserEnum extends Enum
{

    private UserEnum(String s, int i, String name)
    {
        super(s, i);
        this.name = null;
        this.name = name;
    }

    public String getName()
    {
        return name;
    }

    public static UserEnum[] values()
    {
        UserEnum auserenum[];
        int i;
        UserEnum auserenum1[];
        System.arraycopy(auserenum = ENUM$VALUES, 0, auserenum1 = new UserEnum[i = auserenum.length], 0, i);
        return auserenum1;
    }

    public static UserEnum valueOf(String s)
    {
        return (UserEnum)Enum.valueOf(ycl/learn/effective/java/UserEnum, s);
    }

    public static final UserEnum ACTION;
    public static final UserEnum FIRST_NAME;
    public static final UserEnum LAST_NAME;
    public static final UserEnum E_MAIL;
    public static final UserEnum PHONE;
    private String name;
    private static final UserEnum ENUM$VALUES[];

    static 
    {
        ACTION = new UserEnum("ACTION", 0, "ACTION");
        FIRST_NAME = new UserEnum("FIRST_NAME", 1, "FIRST NAME");
        LAST_NAME = new UserEnum("LAST_NAME", 2, "LAST NAME");
        E_MAIL = new UserEnum("E_MAIL", 3, "E-MAIL");
        PHONE = new UserEnum("PHONE", 4, "PHONE");
        ENUM$VALUES = (new UserEnum[] {
            ACTION, FIRST_NAME, LAST_NAME, E_MAIL, PHONE
        });
    }
}
 * so you know enum class first declared the singlton oject, then init it as static.
 * we usually call values(), this method will be rewrite the father's method.
 * and It will be copay to asuserenum1, from 0 to length.[as Type is UserEnum]
 * we also usually call valueOf(String s), this method also mandatory transform type to UserEnum.
 * so let me see see the enum's father.
 * 
 * 
 * public abstract class Enum<E extends Enum<E>>
        implements Comparable<E>, Serializable { 
     * The name of this enum constant, as declared in the enum declaration.
     * Most programmers should use the {@link #toString} method rather than
     * accessing this field. 
    private final String name;
 
     * Returns the name of this enum constant, exactly as declared in its
     * enum declaration.
     * 
     * <b>Most programmers should use the {@link #toString} method in
     * preference to this one, as the toString method may return
     * a more user-friendly name.</b>  This method is designed primarily for
     * use in specialized situations where correctness depends on getting the
     * exact name, which will not vary from release to release.
     *
     * @return the name of this enum constant 
    public final String name() {
	return name;
    } 
     * The ordinal of this enumeration constant (its position
     * in the enum declaration, where the initial constant is assigned
     * an ordinal of zero).
     * 
     * Most programmers will have no use for this field.  It is designed
     * for use by sophisticated enum-based data structures, such as
     * {@link java.util.EnumSet} and {@link java.util.EnumMap}. 
    private final int ordinal;
 
     * Returns the ordinal of this enumeration constant (its position
     * in its enum declaration, where the initial constant is assigned
     * an ordinal of zero).
     * 
     * Most programmers will have no use for this method.  It is
     * designed for use by sophisticated enum-based data structures, such
     * as {@link java.util.EnumSet} and {@link java.util.EnumMap}.
     *
     * @return the ordinal of this enumeration constant 
    public final int ordinal() {
	return ordinal;
    } 
    this method will be call be sun object.
     * Sole constructor.  Programmers cannot invoke this constructor.
     * It is for use by code emitted by the compiler in response to
     * enum type declarations.
     *
     * @param name - The name of this enum constant, which is the identifier
     *               used to declare it.
     * @param ordinal - The ordinal of this enumeration constant (its position
     *         in the enum declaration, where the initial constant is assigned
     *         an ordinal of zero). 
    protected Enum(String name, int ordinal) {
	this.name = name;
	this.ordinal = ordinal;
    } 
     * Returns the name of this enum constant, as contained in the
     * declaration.  This method may be overridden, though it typically
     * isn't necessary or desirable.  An enum type should override this
     * method when a more "programmer-friendly" string form exists.
     *
     * @return the name of this enum constant 
    public String toString() {
	return name;
    }
    use == instead of equal.
     * Returns true if the specified object is equal to this
     * enum constant.
     *
     * @param other the object to be compared for equality with this object.
     * @return  true if the specified object is equal to this
     *          enum constant. 
    public final boolean equals(Object other) { 
        return this==other;
    }
    this is compared with the ordinal.
        public final int compareTo(E o) {
		Enum other = (Enum)o;
		Enum self = this;
		if (self.getClass() != other.getClass() && // optimization
	            self.getDeclaringClass() != other.getDeclaringClass())
		    throw new ClassCastException();
		return self.ordinal - other.ordinal;
	    }	
	    
	 this is the valueof method, will be get enumConstantDirectory() from class, to get the name of enum then return object.
     * Returns the enum constant of the specified enum type with the
     * specified name.  The name must match exactly an identifier used
     * to declare an enum constant in this type.  (Extraneous whitespace
     * characters are not permitted.) 
     *
     * @param enumType the <tt>Class</tt> object of the enum type from which
     *      to return a constant
     * @param name the name of the constant to return
     * @return the enum constant of the specified enum type with the
     *      specified name
     * @throws IllegalArgumentException if the specified enum type has
     *         no constant with the specified name, or the specified
     *         class object does not represent an enum type
     * @throws NullPointerException if <tt>enumType</tt> or <tt>name</tt>
     *         is null
     * @since 1.5 
    public static <T extends Enum<T>> T valueOf(Class<T> enumType,
                                                String name) {
        T result = enumType.enumConstantDirectory().get(name);
        if (result != null)
            return result;
        if (name == null)
            throw new NullPointerException("Name is null");
        throw new IllegalArgumentException(
            "No enum const " + enumType +"." + name);
    }

 * 
 *  
 *  
 * @author e557400
 *
 */
public class StaticFactoryMethod {
	
	Map<String,String> map ;
	
	/**
	 * instance by construction.
	 * @param map
	 */
	public StaticFactoryMethod(Map<String,String> map){
		this.map=map;
	}
	
	/**
	 * instance by static factory method
	 * @return
	 */
	public static StaticFactoryMethod newInstanceByMap(){
		return new StaticFactoryMethod(new HashMap<String,String>());
	}
	

	/**
	 * Boolean and Enum.
	 * The same point is create Object when you init this Object.
	 * and then you can use the created Object, Don't need to create this Object.
	 * This can be shared for hold Application scope, Until the Server is stop.
	 * The JVM is out.
	 * 
	 * This is usually use as tools.
	 * 
	 * @param args
	 */
	public static void main(String[] args) { 
		/**
		 * 1. you need to init params
		 * 2. you can call method by static factory name, very easy to use.
		 */
		StaticFactoryMethod con_sfm = new StaticFactoryMethod(new HashMap<String,String>());
		StaticFactoryMethod method_sfm = StaticFactoryMethod.newInstanceByMap();
		
		/**
		 * 3.when you call the method, you don't need to create object first.
		 */
		List emptyList = Collections.emptyList();//example Java Collections Framework
		Map map =Collections.emptyMap();//example Java Collections Framework
		Comparator comparator = Collections.reverseOrder();//example reverseOrder[c2.compareTo(c1)]
		Comparator reverse_comp = comparator = Collections.reverseOrder(comparator); ///example reverseOrder[cmp.compare(t2, t1)]
		
		ServiceSPI one_serviceSPI = new ServiceSPI(){ 
			public ServiceAPI newService() { 
				return new ServiceAPI(){ 
					public void say() { 
						System.out.println("serviceSPI: one");
					}
					
				};
			} 
		};
		
		ServiceSPI two_serviceSPI = new ServiceSPI(){ 
			public ServiceAPI newService() { 
				return new ServiceAPI(){ 
					public void say() { 
						System.out.println("serviceSPI: two");
					}
					
				};
			} 
		};
		/**
		 * 4. we can call the method with less params.
		 */
		ServiceFramework.registerDefaultSPI(one_serviceSPI);
		ServiceFramework.registerSIP("one", one_serviceSPI);
		ServiceFramework.registerSIP("two", two_serviceSPI);
		//register SPI
		
		ServiceFramework.newInstance().say();
		ServiceFramework.newInstance("one").say();
		ServiceFramework.newInstance("two").say();
		//use difference SPI to get API and call API's method.
		//It is like JDK give Servlet API, and Tomcat implement the API Called
		//Tomcat Servlet Provider Interface, i just call TOMServiceSPI.
		//The ServiceFramework Regiest TOMServiceSPI as Default, so we call 
		//Servlet API, in real that is process as Tomcat Service Implement.
		
	}
	
	/**
	 *API
	 */
	interface ServiceAPI{
		public void say();
	}
	
	/**
	 *SPI
	 */
	interface ServiceSPI{
		ServiceAPI newService();
	}
	
	/**
	 * SPF
	 */
	static class ServiceFramework{
		private ServiceFramework(){}
		private static final ConcurrentMap<String,ServiceSPI> spis = new ConcurrentHashMap<String,ServiceSPI>();
		private static final String DEFAULT_SPI_NAME = "<def>";
		
		public static void registerDefaultSPI(ServiceSPI spi){
			registerSIP(DEFAULT_SPI_NAME,spi);
		}

		public static void registerSIP(String name, ServiceSPI spi) {
			 spis.put(name, spi);
		}
		
		public static ServiceAPI newInstance(){
			return newInstance(DEFAULT_SPI_NAME);
		}

		private static ServiceAPI newInstance(String name) { 
			ServiceSPI spi = spis.get(name);
			if(spi == null){
				throw new IllegalArgumentException("No provider registered with name: " + name);
			}
			return spi.newService();
		}
		
	}

}

分享到:
评论

相关推荐

    FactoryMethodPattern.zip

    简单工厂模式是属于创建型模式,又叫做静态工厂方法(Static Factory Method)模式,但不属于23种GOF设计模式之一。简单工厂模式是由一个工厂对象决定创建出哪一种产品类的实例。简单工厂模式是工厂模式家族中最简单...

    Simple Factory Pattern.rar【GoF的简单工厂模式(C#源码)】

    简单工厂(Simple Factory)模式又称为静态工厂方法(Static Factory Method)模式,属于类的创建型模式,通常它根据自变量的不同返回不同的类的实例。 简单工厂模式的实质是由一个工厂类根据传入的参量,动态决定...

    Android代码-GoogleAutoValue扩展类

    Include auto-value-cursor in your project and add a static factory method to your auto-value object. import com.gabrielittner.auto.value.cursor.ColumnName; @AutoValue public abstract class User { ...

    java 简单工厂模式 源代码

    从设计模式的类型上来说,简单工厂模式是属于创建型模式,又叫做静态工厂方法(Static Factory Method)模式,但不属于23种GOF设计模式之一。简单工厂模式是由一个工厂对象决定创建出哪一种产品类的实例。简单工厂...

    php设计模式之简单工厂模式详解

    1、简单工厂模式(Simple Factory)又叫做 静态工厂方法模式(Static Factory Method) 2、工厂方法模式(Factory Method)又叫做 多态性工厂模式(Polymorphic Factory) 3、抽象工厂模式(Abstract Factory)又叫做 工具...

    Java面试宝典(设计模式,算法,Linux篇).docx

    答: 简单工厂模式是属于创建型模式,又叫做静态工厂方法(Static Factory Method)模式,但不属于23种GOF设计模式之一。简单工厂模式是由一个工厂对象决定创建出哪一种产品类的实例。简单工厂模式是工厂模式家族中最...

    实例讲解PHP设计模式编程中的简单工厂模式

    简单工厂模式是类的创建模式,又叫做静态工厂方法(Static Factory Method)模式。简单工厂模式是由一个工厂对象决定创建出那一种产品类的实例。 1.工厂模式的几种形态 工厂模式专门负责将大量有共同接口的类实例化...

    PHP中的几种设计模式1

    (1)简单工厂模式简单工厂模式又称为静态工厂方法(Static Factory Method)模式,它属于类创建型模式 (2) 工厂方法模式此模式中,通过定义一

    简单工厂经典原码

    简单工厂模式是属于创建型模式,又叫做静态工厂方法(StaticFactory Method)模式,但不属于23种GOF设计模式之一。简单工厂模式是由一个工厂对象决定创建出哪一种产品类的实例。简单工厂模式是工厂模式家族中最简单...

    JAVA设计模式

    简单工厂模式是类的创建模式,又叫做静态工厂方法(Static Factory Method)模式。简单工厂模式是由一个工厂对象决定创建出 哪一种产品类的实例。 工厂方法模式是类的创建模式,又叫做虚拟构造子(Virtual Constructor)...

    Calculator(简单工厂模式)

    从设计模式的类型上来说,简单工厂模式是属于创建型模式,又叫做静态工厂方法(Static Factory Method)模式,但不属于23种GOF设计模式之一。简单工厂模式是由一个工厂对象决定创建出哪一种产品类的实例。简单工厂...

    spring-framework-reference4.1.4

    Instantiation with a static factory method .................................................... 30 Spring Framework 4.0.0.RELEASE Spring Framework Reference Documentation iii Instantiation using an ...

    简单工厂模式 应用

    简单工厂模式(Simple Factory Pattern)属于类的创新型模式,又叫静态工厂方法模式(Static FactoryMethod Pattern),是通过专门定义一个类来负责创建其他类的实例,被创建的实例通常都具有共同的父类。 将“类实例...

    spring-framework-reference-4.1.2

    Instantiation with a static factory method .................................................... 30 Spring Framework 4.0.0.RELEASE Spring Framework Reference Documentation iii Instantiation using an ...

    java 工厂模式的讲解及优缺点的介绍

    主要介绍了java 工厂模式的讲解及优缺点的介绍的相关资料, 简单工厂模式,又称为静态工厂方法(Static Factory Method)模式,它属于类创建型模式,需要的朋友可以参考下

    C#的静态工厂方法与构造函数相比有哪些优缺点

    最近,在与同事进行协同编程时,我们开始讨论在C#中初始化新对象的最佳方法。我一直是使用构造函数实现,...// Using a static factory method IDbConnection myConnection = SqlConnection.FromConnectionString(conn

    PHP设计模式(2017年8月力作)

    Abstract Factory , Builder , Factory Method , Multiton , Pool , Prototype , Simple Factory , Singleton , Static Factory , Structural , Adapter / Wrapper , Bridge , Composite, Data Mapper , Decorator ,...

    抽象工厂模式(Abstract Factory Pattern)

    30 static void Main(string[] args) 31 { 32 //创建一个工厂类的实例 33 string assemblyName = ConfigurationManager.AppSettings["assemblyName"]; 34 string fullTypeName =string.Concat( Configuration...

    在iOS中实现设计模式代码实现

    2. **工厂方法模式(Factory Method Pattern)**: 工厂方法用于创建依赖对象,而不必将对象的创建逻辑暴露给客户端。在iOS中,这可以用于创建视图控制器或其他复杂的对象,这些对象可能有多个变体。 ```swift ...

    java设计模式示例

    1.工厂方法模式(Factory Method) 将程序中创建对象的操作,单独出来处理,创建一个产品的工厂接口,把实际的工作转移到具体的子类。大大提高了系统扩展的柔性,接口的抽象化处理给相互依赖的对象创建提供了最好的...

Global site tag (gtag.js) - Google Analytics