Java設(shè)計(jì)模式期末題是一種測(cè)試應(yīng)聘者對(duì)于Java設(shè)計(jì)模式的理解和應(yīng)用能力的考試。在大多數(shù)情況下,其考查的深度和難度是非常高的。下面就Java設(shè)計(jì)模式期末題的一些樣例題目和答案進(jìn)行介紹。
題目一:
請(qǐng)簡(jiǎn)述單例模式的實(shí)現(xiàn)過(guò)程
答案:?jiǎn)卫J娇梢员WC一個(gè)類只有一個(gè)實(shí)例,并提供一個(gè)全局唯一訪問(wèn)點(diǎn)。可以通過(guò)如下方式來(lái)實(shí)現(xiàn)單例模式:
public class Singleton { private static Singleton instance = null; private Singleton() {} public static Singleton getInstance() { if (instance == null) { synchronized(Singleton.class) { if (instance == null) { instance = new Singleton(); } } } return instance; } }
題目二:
請(qǐng)簡(jiǎn)述裝飾器模式的實(shí)現(xiàn)過(guò)程,以及和代理模式的區(qū)別
答案:裝飾器模式是將對(duì)象功能劃分為較小的自主操作單元,并通過(guò)組合的方式實(shí)現(xiàn)對(duì)類功能的拓展。具體實(shí)現(xiàn)過(guò)程如下:
public interface IComponent { public void operation(); } public class ConcreteComponent implements IComponent { public void operation() { System.out.println("I am a normal component."); } } public abstract class Decorator implements IComponent { protected IComponent component = null; public Decorator(IComponent component) { this.component = component; } public void operation() { if (component != null) { component.operation(); } } } public class ConcreteDecorator1 extends Decorator { public ConcreteDecorator1(IComponent component) { super(component); } public void operation() { super.operation(); System.out.println("I add additional functionalities."); } } public class ConcreteDecorator2 extends Decorator { public ConcreteDecorator2(IComponent component) { super(component); } public void operation() { super.operation(); System.out.println("I add more additional functionalities."); } }
代理模式和裝飾器模式都是為了增加類的功能,但其內(nèi)在原理有所不同。代理模式是由一個(gè)代理類包含一個(gè)原始對(duì)象,通過(guò)代理類間接地訪問(wèn)原始對(duì)象,并在代理類中對(duì)原始對(duì)象的訪問(wèn)進(jìn)行約束和限制。而裝飾器模式則是通過(guò)對(duì)象組合的方式來(lái)增加類的功能,其組合對(duì)象與原始對(duì)象具有相同的接口,通過(guò)組合的方式實(shí)現(xiàn)對(duì)類的功能增加。