1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103
|
interface WindowImpl { void devDrawText(String text); void devDrawRect(int x, int y, int w, int h); void devDrawLine(int x1, int y1, int x2, int y2); }
class LinuxWindowImpl implements WindowImpl { public void devDrawText(String text) { System.out.println("[Linux] Drawing text: " + text); } public void devDrawRect(int x, int y, int w, int h) { System.out.println("[Linux] Drawing rect: " + x + "," + y + "," + w + "," + h); } public void devDrawLine(int x1, int y1, int x2, int y2) { System.out.println("[Linux] Drawing line: " + x1 + "," + y1 + " to " + x2 + "," + y2); } }
class WindowsWindowImpl implements WindowImpl { public void devDrawText(String text) { System.out.println("[Windows] Drawing text: " + text); } public void devDrawRect(int x, int y, int w, int h) { System.out.println("[Windows] Drawing rect: " + x + "," + y + "," + w + "," + h); } public void devDrawLine(int x1, int y1, int x2, int y2) { System.out.println("[Windows] Drawing line: " + x1 + "," + y1 + " to " + x2 + "," + y2); } }
abstract class Window { protected WindowImpl windowImpl;
public Window(WindowImpl windowImpl) { this.windowImpl = windowImpl; }
abstract public void draw(); abstract public void drawText(String text); }
class IconWindow extends Window { public IconWindow(WindowImpl windowImpl) { super(windowImpl); }
public void draw() { windowImpl.devDrawRect(0, 0, 16, 16); windowImpl.devDrawText("Icon"); }
public void drawText(String text) { windowImpl.devDrawText(text); } }
class ApplicationWindow extends Window { public ApplicationWindow(WindowImpl windowImpl) { super(windowImpl); }
public void draw() { windowImpl.devDrawRect(0, 0, 800, 600); windowImpl.devDrawText("Application Window"); windowImpl.devDrawLine(0, 0, 800, 600); }
public void drawText(String text) { windowImpl.devDrawText(text); } }
public class CrossPlatformDemo { public static void main(String[] args) { String os = System.getProperty("os.name").toLowerCase(); WindowImpl impl = os.contains("win") ? new WindowsWindowImpl() : new LinuxWindowImpl();
Window icon = new IconWindow(impl); icon.draw();
Window app = new ApplicationWindow(impl); app.draw(); } }
|