thinking in java中出现的设计模式代码例子


模板模式

例子一:随机创建不同类型的宠物

测试需要的javaBean类

//: typeinfo/pets/Individual.java
package typeinfo.pets;

public class Individual implements Comparable<Individual> {
	private static long counter = 0;
	private final long id = counter++;
	private String name;

	public Individual(String name) {
		this.name = name;
	}

	// 'name' is optional:
	public Individual() {
	}

	public String toString() {
		return getClass().getSimpleName() + (name == null ? "" : " " + name);
	}

	public long id() {
		return id;
	}

	public boolean equals(Object o) {
		return o instanceof Individual && id == ((Individual) o).id;
	}

	public int hashCode() {
		int result = 17;
		if (name != null)
			result = 37 * result + name.hashCode();
		result = 37 * result + (int) id;
		return result;
	}

	public int compareTo(Individual arg) {
		// Compare by class name first:
		String first = getClass().getSimpleName();
		String argFirst = arg.getClass().getSimpleName();
		int firstCompare = first.compareTo(argFirst);
		if (firstCompare != 0)
			return firstCompare;
		if (name != null && arg.name != null) {
			int secondCompare = name.compareTo(arg.name);
			if (secondCompare != 0)
				return secondCompare;
		}
		return (arg.id < id ? -1 : (arg.id == id ? 0 : 1));
	}
} // /:~

//: typeinfo/pets/Person.Java 
package typeinfo.pets;

import typeinfo.pets.Individual;

public class Person extends Individual {
	public Person(String name) {
		super(name);
	}
} // /:-

//: typeinfo/pets/Pet.Java 
package typeinfo.pets;

public class Pet extends Individual {
	public Pet(String name) {
		super(name);
	}

	public Pet() {
		super();
	}
} // /:-

//: typeinfo/pets/Dog.Java 
package typeinfo.pets;

public class Dog extends Pet {
	public Dog(String name) {
		super(name);
	}

	public Dog() {
		super();
	}
} // /:-

//: typeinfo/pets/Mutt.java 
package typeinfo.pets;

public class Mutt extends Dog {
	public Mutt(String name) {
		super(name);
	}

	public Mutt() {
		super();
	}
} // /:-

//: typeinfo/pets/Pug.java 
package typeinfo.pets;

public class Pug extends Dog {
	public Pug(String name) {
		super(name);
	}

	public Pug() {
		super();
	}
} // /:-

//: typeinfo/pets/Cat.java 
package typeinfo.pets;

public class Cat extends Pet {
	public Cat(String name) {
		super(name);
	}

	public Cat() {
		super();
	}
}

//: typeinfo/pets/EgyptianMau.java 
package typeinfo.pets;

public class EgyptianMau extends Cat {
	public EgyptianMau(String name) {
		super(name);
	}

	public EgyptianMau() {
		super();
	}
} // /:-

//: typeinfo/pets/Manx.java 
package typeinfo.pets;

public class Manx extends Cat {
	public Manx(String name) {
		super(name);
	}

	public Manx() {
		super();
	}
}

//: typeinfo/pets/Cymric.java 
package typeinfo.pets;

public class Cymric extends Manx {
	public Cymric(String name) {
		super(name);
	}

	public Cymric() {
		super();
	}
} // /:-

//: typeinfo/pets/Rodent.java 
package typeinfo.pets;

public class Rodent extends Pet {
	public Rodent(String name) {
		super(name);
	}

	public Rodent() {
		super();
	}
} // /:-

//: typeinfo/pets/Rat.java 
package typeinfo.pets;

public class Rat extends Rodent {
	public Rat(String name) {
		super(name);
	}

	public Rat() {
		super();
	}
} // /:-

//: typeinfo/pets/Mouse.Java 
package typeinfo.pets;

public class Mouse extends Rodent {
	public Mouse(String name) {
		super(name);
	}

	public Mouse() {
		super();
	}
} // /:-

//: typeinfo/pets/Hamster.Java 
package typeinfo.pets;

public class Hamster extends Rodent {
	public Hamster(String name) {
		super(name);
	}

	public Hamster() {
		super();
	}
}

核心类

 we need a way to randomly create different types of pets, and for convenience, to create arrays and Lists of pets. To allow this tool to evolve through several different implementations, we'll define it as an abstract class:
//: typeinfo/pets/PetCreator.Java 
// Creates random sequences of Pets, 
package typeinfo.pets;

import java.util.*;

public abstract class PetCreator {
	private Random rand = new Random(47);

	// The List of the different types of Pet to create:
	public abstract List<Class<? extends Pet>> types();

	public Pet randomPet() { // Create one random Pet
		int n = rand.nextInt(types().size());
		try {
			return types().get(n).newInstance();
		} catch (InstantiationException e) {
			throw new RuntimeException(e);
		} catch (IllegalAccessException e) {
			throw new RuntimeException(e);
		}
	}

	public Pet[] createArray(int size) {
		Pet[] result = new Pet[size];
		for (int i = 0; i < size; i++)
			result[i] = randomPet();
		return result;
	}

	public ArrayList<Pet> arrayList(int size) {
		ArrayList<Pet> result = new ArrayList<Pet>();
		Collections.addAll(result, createArray(size));
		return result;
	}
} // /:-

模板的实现类(第一种方式)

//: typeinf0/pets/ForNameCreator.Java 
package typeinfo.pets;

import java.util.*;

public class ForNameCreator extends PetCreator {
	private static List<Class<? extends Pet>> types = new ArrayList<Class<? extends Pet>>();
	// Types that you want to be randomly created:
	private static String[] typeNames = { "typeinfo.pets.Mutt",
			"typeinfo.pets.Pug", "typeinfo.pets.EgyptianMau",
			"typei nfo.pets.Manx", "typeinfo.pets.Cymric",
			"typei nfo.pets.Rat", "typeinfo.pets.Mouse",
			"typeinfo.pets.Hamster" };

	@SuppressWarnings("unchecked")
	private static void loader() {
		try {
			for (String name : typeNames)
				types.add((Class<? extends Pet>) Class.forName(name));
		} catch (ClassNotFoundException e) {
			throw new RuntimeException(e);
		}
	}

	static {
		loader();
	}

	public List<Class<? extends Pet>> types() {
		return types;
	}
} // /: -

模板的实现类(第二种方式)

//: typeinfo/pets/LiteralPetCreator.java 
// Using class literals, 
package typeinfo.pets;

import java.util.Arrays;
import java.util.Collections;
import java.util.List;

public class LiteralPetCreator extends PetCreator {
	// No try block needed.
	@SuppressWarnings("unchecked")
	public static final List<Class<? extends Pet>> allTypes = Collections
			.unmodifiableList(Arrays.asList(Pet.class, Dog.class, Cat.class,
					Rodent.class, Mutt.class, Pug.class, EgyptianMau.class,
					Manx.class, Cymric.class, Rat.class, Mouse.class,
					Hamster.class));
	// Types for random creation:
	private static final List<Class<? extends Pet>> types = allTypes.subList(
			allTypes.indexOf(Mutt.class), allTypes.size());

	public List<Class<? extends Pet>> types() {
		return types;
	}

	public static void main(String[] args) {
		System.out.println(types);
	}
}

总结

使用模板设计模式的原因是让子类可以自定义自己的类型列表

门面模式

//: typeinfo/pets/Pets.java 
// Facade to produce a default PetCreator. 
package typeinfo.pets;

import java.util.*;

public class Pets {
	public static final PetCreator creator = new LiteralPetCreator();

	public static Pet randomPet() {
		return creator.randomPet();
	}

	public static Pet[] createArray(int size) {
		return creator.createArray(size);
	}

	public static ArrayList<Pet> arrayList(int size) {
		return creator.arrayList(size);
	}
} // /:-

门面模式的使用

package typeinfo.pets;

import typeinfo.PetCount;

//: typeinfo/PetCount2.java 
public class PetCount2 {
	public static void main(String[] args) {
		PetCount.countPets(Pets.creator);
	}
} /* (Execute to see output) */// :-

工厂模式

// : typeinfo/factory/Factory.Java
package typeinfo.factory; 
public interface Factory<T> { T create(); }

package typeinfo.factory;

// : type info/RegisteredFactories.jav a 
// Registering Class Factories in the base class. 
import java.util.ArrayList;
import java.util.List;
import java.util.Random;

class Part {
	public String toString() {
		return getClass().getSimpleName();
	}

	static List<Factory<? extends Part>> partFactories = new ArrayList<Factory<? extends Part>>();
	static {
		// Collections.addAll() gives an "unchecked generic
		// array creation ... for varargs parameter" warning.
		partFactories.add(new FuelFilter.Factory());
		partFactories.add(new AirFilter.Factory());
		partFactories.add(new CabinAirFilter.Factory());
		partFactories.add(new OilFilter.Factory());
		partFactories.add(new FanBelt.Factory());
		partFactories.add(new PowerSteeringBelt.Factory());
		partFactories.add(new GeneratorBelt.Factory());
	}
	private static Random rand = new Random(47);

	public static Part createRandom() {
		int n = rand.nextInt(partFactories.size());
		return partFactories.get(n).create();
	}
}

class Filter extends Part {
}

class FuelFilter extends Filter {
	// Create a Class Factory for each specific type:
	public static class Factory implements typeinfo.factory.Factory<FuelFilter> {
		public FuelFilter create() {
			return new FuelFilter();
		}
	}
}

class AirFilter extends Filter {
	public static class Factory implements typeinfo.factory.Factory<AirFilter> {
		public AirFilter create() {
			return new AirFilter();
		}
	}
}

class CabinAirFilter extends Filter {
	public static class Factory implements
			typeinfo.factory.Factory<CabinAirFilter> {
		public CabinAirFilter create() {
			return new CabinAirFilter();
		}
	}
}

class OilFilter extends Filter {
	public static class Factory implements typeinfo.factory.Factory<OilFilter> {
		public OilFilter create() {
			return new OilFilter();
		}
	}
}

class Belt extends Part {
}

class FanBelt extends Belt {
	public static class Factory implements typeinfo.factory.Factory<FanBelt> {
		public FanBelt create() {
			return new FanBelt();
		}
	}
}

class GeneratorBelt extends Belt {
	public static class Factory implements
			typeinfo.factory.Factory<GeneratorBelt> {
		public GeneratorBelt create() {
			return new GeneratorBelt();
		}
	}
}

class PowerSteeringBelt extends Belt {
	public static class Factory implements
			typeinfo.factory.Factory<PowerSteeringBelt> {
		public PowerSteeringBelt create() {
			return new PowerSteeringBelt();
		}
	}
}

public class RegisteredFactories {
	public static void main(String[] args) {
		for (int i = 0; i < 10; i++)
			System.out.println(Part.createRandom());
	}
}




  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值