工厂模式

  1. interface Human{
  2. public void eat();
  3. public void sleep();
  4. public void beat();
  5. }
  6. // 创建实现类 Male
  7. class Male implements Human{
  8. public void eat(){
  9. System.out.println("Male can eat.");
  10. }
  11. public void sleep(){
  12. System.out.println("Male can sleep.");
  13. }
  14. public void beat(){
  15. System.out.println("Male can beat.");
  16. }
  17. }
  18. //创建实现类 Female
  19. class Female implements Human{
  20. public void eat(){
  21. System.out.println("Female can eat.");
  22. }
  23. public void sleep(){
  24. System.out.println("Female can sleep.");
  25. }
  26. public void beat(){
  27. System.out.println("Female can beat.");
  28. }
  29. }
  30. // 创建普通工厂类
  31. class HumanFactory{
  32. public Human createHuman(String gender){
  33. if( gender.equals("male") ){
  34. return new Male();
  35. }else if( gender.equals("female")){
  36. return new Female();
  37. }else {
  38. System.out.println("请输入正确的类型!");
  39. return null;
  40. }
  41. }
  42. }
  43. // 工厂测试类
  44. public class FactoryTest {
  45. public static void main(String[] args){
  46. HumanFactory factory = new HumanFactory();
  47. Human male = factory.createHuman("male");
  48. male.eat();
  49. male.sleep();
  50. male.beat();
  51. }
  52. }

多个工厂模式

  1. // 多个工厂方法
  2. public class HumanFactory{
  3. public Male createMale() {
  4. return new Male();
  5. }
  6. public Female createFemale() {
  7. return new Female();
  8. }
  9. }
  10. // 工厂测试类
  11. public class FactoryTest {
  12. public static void main(String[] args){
  13. HumanFactory factory = new HumanFactory();
  14. Human male = factory.createMale();
  15. male.eat();
  16. male.sleep();
  17. male.beat();
  18. }
  19. }

静态工厂模式

  1. // 多个工厂方法
  2. public class HumanFactory{
  3. public static Male createMale() {
  4. return new Male();
  5. }
  6. public static Female createFemale() {
  7. return new Female();
  8. }
  9. }
  10. // 工厂测试类
  11. public class FactoryTest {
  12. public static void main(String[] args){
  13. Human male = HumanFactory.createMale();
  14. male.eat();
  15. male.sleep();
  16. male.beat();
  17. }
  18. }

工厂模式应用

  1. java.util.Calendar - getInstance()
  2. java.util.Calendar - getInstance(TimeZone zone)
  3. java.util.Calendar - getInstance(Locale aLocale)
  4. java.util.Calendar - getInstance(TimeZone zone, Locale aLocale)
  5. java.text.NumberFormat - getInstance()
  6. java.text.NumberFormat - getInstance(Locale inLocale)