⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 word.java

📁 内存受限系统软件开发一书的代码。(虽不及Gang of Four的模式掷地有声
💻 JAVA
字号:

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 + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -