简单工厂方法实现

简单工厂方法并不属于真正的设计模式
  • 首先创建所有鸟类的祖先类
  • package com.simplyFactory;
    
    public interface Bird {
    	public void fly();
    	public void sing();
    
    }
    

  • 创建两个实现类Eagle和Dove
  • package com.simplyFactory;
    
    public class Eagle implements Bird {
    
    	public void fly() {
    		System.out.println("I am eagle, I can fly high");
    	}
    
    	public void sing() {
    		System.out.println("I can sing loud");
    	}
    }
    
    

    package com.simplyFactory;
    
    public class Dove implements Bird {
    
    	public void fly() {
    		System.out.println("I am a dove, I can fly");
    	}
    
    	public void sing() {
    		System.out.println("I am a dove , I can't sing");
    	}
    
    }
    

  • 定义简单鸟类工厂SimpleBirdFactory
  • package com.simplyFactory;
    
    public class SimpleBirdFactory {
    	public static Bird createBird(String type) {
    		Bird bird = null;
    		
    		if (type.equals("dove")) {
    			bird = new Dove();
    		} else if (type.equals("eagle")) {
    			bird = new Eagle();
    		}
    		return bird;
    	}
    
    }
    
    

  • 编写测试程序
  • package com.simplyFactory;
    
    public class testFactory {
    
    	public static void main(String[] args) {
    				
    		Bird dove = SimpleBirdFactory.createBird("dove");
    		dove.fly();
    		dove.sing();
    		
    		Bird eagle = SimpleBirdFactory.createBird("eagle");
    		eagle.fly();
    		eagle.sing();
    		
    	}
    }
    
    


  • 总结
  • 1.工厂方法可以静态,也可以非静态,用静态的话不需要实例化一个工厂
    2.简单工厂封装了具体实现

    你可能感兴趣的:(java,设计模式)