设计模式研习手记:简单工厂模式(Simple Factory)

简单工厂模式(Simple Factory)又叫静态工厂方法模式。它定义了一个具体的工厂类来负责创建一些类的实例,而这些被创建的类都应该有一个共同的父类。

下面是一个利用简单工厂模式创建Tiger,Dolphin,Parrot的例子,这些具体的动物类都实现了抽象的动物接口。

 

//****Animal.java 
package com.designpattern; 
public interface Animal { 
    public void eat(); 
}

 

 

//****Tiger.java 
package com.designpattern; 
public class Tiger implements Animal { 
    public void run() { 
        System.out.println("Tiger is running!"); 
    } 
    
    public void eat() { 
        System.out.println("Tiger is eating!"); 
    } 
}

 

 

//****Dolphin.java 
package com.designpattern; 
public class Dolphin implements Animal { 
    public void swim() { 
        System.out.println("Dolphin is swimming!"); 
    } 

    public void eat() { 
        System.out.println("Dolphin is eating!"); 
    } 
}

 

 

//****Parrot.java 
package com.designpattern; 
public class Parrot implements Animal { 
    public void fly() { 
        System.out.println("Parrot is flying!"); 
    } 

    public void eat() { 
        System.out.println("Parrot is eating!"); 
    } 
}

 

//****SimpleFactory.java
package com.designpattern;
public class SimpleFactory {
	/*in terms of parameter to create different objects*/
	public static Animal createAnimal(String animalName){
		if("Tiger".equals(animalName))
			return new Tiger();
		else if("Dolphin".equals(animalName))
			return new Dolphin();
		else if("Parrot".equals(animalName)) 
			return new Parrot();
	}
}

 

//****Client.java
package com.designpattern;
public class Client {
	public static void main(String[] args){
		Animal animal = SimpleFactory.createAnimal("Tiger");
		animal.eat();
		Animal animal = SimpleFactory.createAnimal("Dolphin");
		animal.eat();
		Animal animal = SimpleFactory.createAnimal("Parrot");
		animal.eat();
	}
}

 

 

//****输出****
Tiger is eating!
Dolphin is eating!
Parrot is eating!

 

总结:

简单工厂模式中,客户端不再负责对象的创建,具体的工厂类用来创建对象,客户端只负责对对象的调用。

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