Factory(Factory Method)

来源:互联网 发布:全能数据恢复免费版 编辑:程序博客网 时间:2024/06/05 10:42
 

/**
 *
 */
package com.sean.factory.method;

import com.sean.factory.Sex;

/**
 * @author Sean_Zhang
 *
 */
public interface IPerson {
 public String getName();
 
 public Sex getSex();
}

/**
 *
 */
package com.sean.factory.method;

import com.sean.factory.Names;
import com.sean.factory.Sex;

/**
 * @author Sean_Zhang
 *
 */
public abstract class Person implements IPerson {

 public String getName() {
  String name = null;
  if(this.getSex() == Sex.MALE) {
   name = Names.MAN.getName();
  } else if(this.getSex() == Sex.FEMALE) {
   name = Names.WOMAN.getName();
  }
  return name;
 }
}

 

/**
 *
 */
package com.sean.factory.method;

import com.sean.factory.Sex;

/**
 * @author Sean_Zhang
 *
 */
public class Man extends Person {

 /* (non-Javadoc)
  * @see com.sean.factory.method.IPerson#getSex()
  */
 public Sex getSex() {
  return Sex.MALE;
 }

}

/**
 *
 */
package com.sean.factory.method;

import com.sean.factory.Sex;

/**
 * @author Sean_Zhang
 *
 */
public class Woman extends Person {

 /* (non-Javadoc)
  * @see com.sean.factory.method.IPerson#getSex()
  */
 public Sex getSex() {
  return Sex.FEMALE;
 }

}

 

package com.sean.factory.method;

import com.sean.factory.Sex;
import com.sean.factory.simple.IPerson;
import com.sean.factory.simple.Man;
import com.sean.factory.simple.Woman;

public class PersonMethodFactory {
 public static IPerson getPerson(Sex sex) {
  IPerson person = null;
  if(sex == Sex.MALE) {
   person = new Man();
  } else if(sex == Sex.FEMALE) {
   person = new Woman();
  }
  return person;
 }
}

 JDK Examples:

  • java.lang.Proxy#newProxyInstance()
  • java.lang.Object#toString()
  • java.lang.Class#newInstance()
  • java.lang.reflect.Array#newInstance()
  • java.lang.reflect.Constructor#newInstance()
  • java.lang.Boolean#valueOf(String)
  • java.lang.Class#forName()

 

原创粉丝点击