word.java

来自「内存受限系统软件开发一书的代码。(虽不及Gang of Four的模式掷地有声」· Java 代码 · 共 78 行

JAVA
78
字号

public class Word 
{
    public String AsString()    { return rep.AsString(); }
    public byte[] AsSound()     { return rep.AsSound(); }
    public void BecomeSound()   { rep.BecomeSound(); }
    public void BecomeDefault() { rep.BecomeDefault(); }

    public Word( String aWord )
    { Become( new DefaultWordImplementation( this, aWord ) ); }
    public void Become( WordInterface aRep )
    { rep = aRep; }
    private
        WordInterface rep;

    public static void main(String s[]) { Test.DoTest(); }
};

interface WordInterface
{
    public byte[] AsSound();
    public String AsString();
    public void BecomeSound();
    public void BecomeDefault();
};

class DefaultWordImplementation implements WordInterface
{
    public DefaultWordImplementation( Word aBridge, String aWord )
    { bridge = aBridge; word = aWord; }
    
    public DefaultWordImplementation( Word aBridge, WordInterface aRep )
    { bridge = aBridge; word = aRep.AsString(); }

    public String AsString() { return word; }
    public void BecomeSound() {
        bridge.Become( new SoundWordImplementation( bridge, this ) );
    }
    public void BecomeDefault() {}
    public byte[] AsSound() 
    { 
        BecomeSound();
        return bridge.AsSound(); 
    }

    private String word;
    private Word bridge;
};

class SoundWordImplementation implements WordInterface
{
    SoundWordImplementation( Word aBridge, WordInterface prevRep )
    { bridge = aBridge; word = prevRep.AsString(); /* sound = Something() */ }
    public String AsString() { return word; }
    public byte[] AsSound()  { return sound; }
    public void BecomeDefault() {
        bridge.Become( new DefaultWordImplementation( bridge, this ) );
    }
    public void BecomeSound() {}

    private String word;
    private Word bridge;
    private byte[] sound;
};

class Test
{
    public static void DoTest()
    {
        Word x = new Word( "Hello" );
        System.out.println( x.AsString() );
        byte[] y = x.AsSound();
        System.out.println( x.AsString() );
        x.BecomeDefault();
        System.out.println( x.AsString() );
    }
};

⌨️ 快捷键说明

复制代码Ctrl + C
搜索代码Ctrl + F
全屏模式F11
增大字号Ctrl + =
减小字号Ctrl + -
显示快捷键?