工厂设计模式(Factory):
常规程序接口示例:
interface IFood{
void eat();
}
class Bread implements IFood{
public void eat(){
System.out.println("吃面包");
}
}
class Untitled {
public static void main(String[] args) {
IFood food = new Bread();
food.eat();
}
}
关键代码:IFood food = new Bread();
缺点:客户端需要明确的知道具体子类。如果更改别的需要更改客户端代码。
例如:
class Milk implements IFood{ public void eat(){ System.out.println(“喝牛奶”); }
class Untitled {
public static void main(String[] args) {
IFood food = new Milk();
food.eat();
}
}
将food实例化的对象从Bread->Milk。
工厂模式范例:
interface IFood{
void eat();
}
class Bread implements IFood{
public void eat(){
System.out.println("吃面包");
}
}
class Milk implements IFood{
public void eat(){
System.out.println("喝牛奶");
}
}
class Factory{
public static IFood getInstance(String className){
if ("bread".equals(className)) {
return new Bread();
}
if ("milk".equals(className)) {
return new Bread();
}
return null;
}
}
class Untitled {
public static void main(String[] args) {
IFood food = Factory.getInstance(args[0]);
food.eat();
}
}
总结:主类只关心工厂类和接口类,不需要关心实现接口的更多子类,达到降低耦合的目的。
代理设计模式(Proxy):
帮助用户将所有开发注意力只集中在核心业务功能上。
实现代理设计:
interface IEat{
void get();
}
class EatReal implements IEat{
public void get(){
System.out.println("真实主题:得到食物,开始品尝");
}
}
class EatProxy implements IEat{
private IEat eat;
public void get(){
this.prepare();
this.eat.get();
this.clear();
}
public EatProxy(IEat eat){
this.eat = eat;
}
public void prepare(){
System.out.println("1");
System.out.println("2");
System.out.println("3");
}
public void clear(){
System.out.println("4");
}
}
class Untitled {
public static void main(String[] args) {
IEat eat = new EatProxy(new EatReal());
eat.get();
/*
1
2
3
真实主题:得到食物,开始品尝
4
*/
}
}