├── readme.txt └── src ├── AbstractFactory ├── A2 │ ├── Main.java │ ├── factory │ │ ├── Factory.java │ │ ├── Item.java │ │ ├── Link.java │ │ ├── Page.java │ │ └── Tray.java │ ├── listfactory │ │ ├── ListFactory.java │ │ ├── ListLink.java │ │ ├── ListPage.java │ │ └── ListTray.java │ └── tablefactory │ │ ├── TableFactory.java │ │ ├── TableLink.java │ │ ├── TablePage.java │ │ └── TableTray.java └── Sample │ ├── Main.java │ ├── factory │ ├── Factory.java │ ├── Item.java │ ├── Link.java │ ├── Page.java │ └── Tray.java │ ├── listfactory │ ├── ListFactory.java │ ├── ListLink.java │ ├── ListPage.java │ └── ListTray.java │ └── tablefactory │ ├── TableFactory.java │ ├── TableLink.java │ ├── TablePage.java │ └── TableTray.java ├── Adapter ├── A2 │ ├── FileIO.java │ ├── FileProperties.java │ ├── Main.java │ └── file.txt ├── Q2 │ ├── FileIO.java │ ├── Main.java │ ├── file.txt │ └── newfile.txt ├── Sample1 │ ├── Banner.java │ ├── Main.java │ ├── Print.java │ └── PrintBanner.java └── Sample2 │ ├── Banner.java │ ├── Main.java │ ├── Print.java │ └── PrintBanner.java ├── Bridge ├── A1 │ ├── CountDisplay.java │ ├── Display.java │ ├── DisplayImpl.java │ ├── Main.java │ ├── RandomCountDisplay.java │ └── StringDisplayImpl.java ├── A2 │ ├── CountDisplay.java │ ├── Display.java │ ├── DisplayImpl.java │ ├── FileDisplayImpl.java │ ├── Main.java │ ├── RandomCountDisplay.java │ ├── StringDisplayImpl.java │ └── star.txt ├── A3 │ ├── CharDisplayImpl.java │ ├── CountDisplay.java │ ├── Display.java │ ├── DisplayImpl.java │ ├── IncreaseDisplay.java │ ├── Main.java │ └── StringDisplayImpl.java └── Sample │ ├── CountDisplay.java │ ├── Display.java │ ├── DisplayImpl.java │ ├── Main.java │ └── StringDisplayImpl.java ├── Builder ├── A2 │ ├── Builder.java │ ├── Director.java │ ├── HTMLBuilder.java │ ├── Main.java │ └── TextBuilder.java ├── A3 │ ├── Builder.java │ ├── Director.java │ ├── FrameBuilder.java │ └── Main.java ├── A4 │ ├── Builder.java │ ├── Director.java │ ├── HTMLBuilder.java │ ├── Main.java │ └── TextBuilder.java └── Sample │ ├── Builder.java │ ├── Director.java │ ├── HTMLBuilder.java │ ├── Main.java │ └── TextBuilder.java ├── ChainOfResponsibility ├── A4 │ ├── LimitSupport.java │ ├── Main.java │ ├── NoSupport.java │ ├── OddSupport.java │ ├── SpecialSupport.java │ ├── Support.java │ └── Trouble.java └── Sample │ ├── LimitSupport.java │ ├── Main.java │ ├── NoSupport.java │ ├── OddSupport.java │ ├── SpecialSupport.java │ ├── Support.java │ └── Trouble.java ├── Command ├── A1 │ ├── Main.java │ ├── command │ │ ├── Command.java │ │ └── MacroCommand.java │ └── drawer │ │ ├── ColorCommand.java │ │ ├── DrawCanvas.java │ │ ├── DrawCommand.java │ │ └── Drawable.java ├── A2 │ ├── Main.java │ ├── command │ │ ├── Command.java │ │ └── MacroCommand.java │ └── drawer │ │ ├── DrawCanvas.java │ │ ├── DrawCommand.java │ │ └── Drawable.java ├── A3 │ ├── Main.java │ ├── command │ │ ├── Command.java │ │ └── MacroCommand.java │ └── drawer │ │ ├── DrawCanvas.java │ │ ├── DrawCommand.java │ │ └── Drawable.java └── Sample │ ├── Main.java │ ├── command │ ├── Command.java │ └── MacroCommand.java │ └── drawer │ ├── DrawCanvas.java │ ├── DrawCommand.java │ └── Drawable.java ├── Composite ├── A2 │ ├── Directory.java │ ├── Entry.java │ ├── File.java │ ├── FileTreatmentException.java │ └── Main.java └── Sample │ ├── Directory.java │ ├── Entry.java │ ├── File.java │ ├── FileTreatmentException.java │ └── Main.java ├── Decorator ├── A1 │ ├── Border.java │ ├── Display.java │ ├── FullBorder.java │ ├── Main.java │ ├── SideBorder.java │ ├── StringDisplay.java │ └── UpDownBorder.java ├── A2 │ ├── Border.java │ ├── Display.java │ ├── FullBorder.java │ ├── Main.java │ ├── MultiStringDisplay.java │ ├── SideBorder.java │ └── StringDisplay.java ├── Q1 │ └── Main.java ├── Q2 │ └── Main.java └── Sample │ ├── Border.java │ ├── Display.java │ ├── FullBorder.java │ ├── Main.java │ ├── SideBorder.java │ └── StringDisplay.java ├── Facade ├── A2 │ ├── Main.java │ ├── maildata.txt │ └── pagemaker │ │ ├── Database.java │ │ ├── HtmlWriter.java │ │ └── PageMaker.java ├── Q2 │ └── Main.java └── Sample │ ├── Main.java │ ├── maildata.txt │ └── pagemaker │ ├── Database.java │ ├── HtmlWriter.java │ └── PageMaker.java ├── FactoryMethod ├── A2 │ ├── Main.java │ ├── framework │ │ ├── Factory.java │ │ └── Product.java │ └── idcard │ │ ├── IDCard.java │ │ └── IDCardFactory.java └── Sample │ ├── Main.java │ ├── framework │ ├── Factory.java │ └── Product.java │ └── idcard │ ├── IDCard.java │ └── IDCardFactory.java ├── Flyweight ├── A1 │ ├── BigChar.java │ ├── BigCharFactory.java │ ├── BigString.java │ ├── Main.java │ ├── big-.txt │ ├── big0.txt │ ├── big1.txt │ ├── big2.txt │ ├── big3.txt │ ├── big4.txt │ ├── big5.txt │ ├── big6.txt │ ├── big7.txt │ ├── big8.txt │ └── big9.txt ├── A2 │ ├── BigChar.java │ ├── BigCharFactory.java │ ├── BigString.java │ ├── Main.java │ ├── big-.txt │ ├── big0.txt │ ├── big1.txt │ ├── big2.txt │ ├── big3.txt │ ├── big4.txt │ ├── big5.txt │ ├── big6.txt │ ├── big7.txt │ ├── big8.txt │ └── big9.txt └── Sample │ ├── BigChar.java │ ├── BigCharFactory.java │ ├── BigString.java │ ├── Main.java │ ├── big-.txt │ ├── big0.txt │ ├── big1.txt │ ├── big2.txt │ ├── big3.txt │ ├── big4.txt │ ├── big5.txt │ ├── big6.txt │ ├── big7.txt │ ├── big8.txt │ └── big9.txt ├── Interpreter ├── A1 │ ├── Main.java │ ├── language │ │ ├── CommandListNode.java │ │ ├── CommandNode.java │ │ ├── Context.java │ │ ├── ExecuteException.java │ │ ├── Executor.java │ │ ├── ExecutorFactory.java │ │ ├── InterpreterFacade.java │ │ ├── Node.java │ │ ├── ParseException.java │ │ ├── PrimitiveCommandNode.java │ │ ├── ProgramNode.java │ │ └── RepeatCommandNode.java │ └── turtle │ │ └── TurtleCanvas.java └── Sample │ ├── CommandListNode.java │ ├── CommandNode.java │ ├── Context.java │ ├── Main.java │ ├── Node.java │ ├── ParseException.java │ ├── PrimitiveCommandNode.java │ ├── ProgramNode.java │ ├── RepeatCommandNode.java │ └── program.txt ├── Iterator ├── A1 │ ├── Aggregate.java │ ├── Book.java │ ├── BookShelf.java │ ├── BookShelfIterator.java │ ├── Iterator.java │ └── Main.java └── Sample │ ├── Aggregate.java │ ├── Book.java │ ├── BookShelf.java │ ├── BookShelfIterator.java │ ├── Iterator.java │ └── Main.java ├── Mediator ├── A1 │ ├── Colleague.java │ ├── ColleagueButton.java │ ├── ColleagueCheckbox.java │ ├── ColleagueTextField.java │ ├── LoginFrame.java │ ├── Main.java │ └── Mediator.java └── Sample │ ├── Colleague.java │ ├── ColleagueButton.java │ ├── ColleagueCheckbox.java │ ├── ColleagueTextField.java │ ├── LoginFrame.java │ ├── Main.java │ └── Mediator.java ├── Memento ├── A4 │ ├── Main.java │ └── game │ │ ├── Gamer.java │ │ └── Memento.java └── Sample │ ├── Main.java │ └── game │ ├── Gamer.java │ └── Memento.java ├── Observer ├── A1 │ ├── DigitObserver.java │ ├── GraphObserver.java │ ├── IncrementalNumberGenerator.java │ ├── Main.java │ ├── NumberGenerator.java │ ├── Observer.java │ └── RandomNumberGenerator.java ├── A2 │ ├── DigitObserver.java │ ├── FrameObserver.java │ ├── GraphObserver.java │ ├── Main.java │ ├── NumberGenerator.java │ ├── Observer.java │ └── RandomNumberGenerator.java ├── Q1 │ └── Main.java └── Sample │ ├── DigitObserver.java │ ├── GraphObserver.java │ ├── Main.java │ ├── NumberGenerator.java │ ├── Observer.java │ └── RandomNumberGenerator.java ├── Prototype └── Sample │ ├── Main.java │ ├── MessageBox.java │ ├── UnderlinePen.java │ └── framework │ ├── Manager.java │ └── Product.java ├── Proxy ├── A1 │ ├── Main.java │ ├── Printable.java │ ├── Printer.java │ └── PrinterProxy.java └── Sample │ ├── Main.java │ ├── Printable.java │ ├── Printer.java │ └── PrinterProxy.java ├── Singleton ├── A1 │ ├── Main.java │ └── TicketMaker.java ├── A2 │ ├── Main.java │ └── Triple.java ├── A3_1 │ ├── Main.java │ └── Singleton.java ├── A3_2 │ ├── Main.java │ └── Singleton.java ├── Q1 │ └── TicketMaker.java ├── Q3 │ └── Singleton.java └── Sample │ ├── Main.java │ └── Singleton.java ├── State ├── A3 │ ├── Context.java │ ├── DayState.java │ ├── Main.java │ ├── NightState.java │ ├── NoonState.java │ ├── SafeFrame.java │ └── State.java ├── A4 │ ├── Context.java │ ├── DayState.java │ ├── Main.java │ ├── NightState.java │ ├── SafeFrame.java │ ├── State.java │ └── UrgentState.java └── Sample │ ├── Context.java │ ├── DayState.java │ ├── Main.java │ ├── NightState.java │ ├── SafeFrame.java │ └── State.java ├── Strategy ├── A1 │ ├── Hand.java │ ├── Main.java │ ├── Player.java │ ├── ProbStrategy.java │ ├── RandomStrategy.java │ └── Strategy.java ├── A4 │ ├── Main.java │ ├── QuickSorter.java │ ├── SortAndPrint.java │ └── Sorter.java ├── Q4 │ ├── Main.java │ ├── SelectionSorter.java │ ├── SortAndPrint.java │ └── Sorter.java └── Sample │ ├── Hand.java │ ├── Main.java │ ├── Player.java │ ├── ProbStrategy.java │ ├── Strategy.java │ └── WinningStrategy.java ├── TemplateMethod └── Sample │ ├── AbstractDisplay.java │ ├── CharDisplay.java │ ├── Main.java │ └── StringDisplay.java └── Visitor ├── A1 ├── Directory.java ├── Element.java ├── Entry.java ├── File.java ├── FileFindVisitor.java ├── FileTreatmentException.java ├── ListVisitor.java ├── Main.java └── Visitor.java ├── A2 ├── Directory.java ├── Element.java ├── Entry.java ├── File.java ├── FileTreatmentException.java ├── ListVisitor.java ├── Main.java ├── SizeVisitor.java └── Visitor.java ├── A3 ├── Directory.java ├── Element.java ├── ElementArrayList.java ├── Entry.java ├── File.java ├── FileTreatmentException.java ├── ListVisitor.java ├── Main.java └── Visitor.java ├── Q1 └── Main.java ├── Q3 └── Main.java └── Sample ├── Directory.java ├── Element.java ├── Entry.java ├── File.java ├── FileTreatmentException.java ├── ListVisitor.java ├── Main.java └── Visitor.java /src/AbstractFactory/A2/Main.java: -------------------------------------------------------------------------------- 1 | import factory.*; 2 | 3 | public class Main { 4 | public static void main(String[] args) { 5 | if (args.length != 1) { 6 | System.out.println("Usage: java Main class.name.of.ConcreteFactory"); 7 | System.out.println("Example 1: java Main listfactory.ListFactory"); 8 | System.out.println("Example 2: java Main tablefactory.TableFactory"); 9 | System.exit(0); 10 | } 11 | Factory factory = Factory.getFactory(args[0]); 12 | Page page = factory.createYahooPage(); 13 | page.output(); 14 | } 15 | } 16 | -------------------------------------------------------------------------------- /src/AbstractFactory/A2/factory/Factory.java: -------------------------------------------------------------------------------- 1 | package factory; 2 | 3 | public abstract class Factory { 4 | public static Factory getFactory(String classname) { 5 | Factory factory = null; 6 | try { 7 | factory = (Factory)Class.forName(classname).newInstance(); 8 | } catch (ClassNotFoundException e) { 9 | System.err.println("没有找到 " + classname + "类。"); 10 | } catch (Exception e) { 11 | e.printStackTrace(); 12 | } 13 | return factory; 14 | } 15 | public abstract Link createLink(String caption, String url); 16 | public abstract Tray createTray(String caption); 17 | public abstract Page createPage(String title, String author); 18 | public Page createYahooPage() { 19 | Link link = createLink("Yahoo!", "http://www.yahoo.com/"); 20 | Page page = createPage("Yahoo!", "Yahoo!"); 21 | page.add(link); 22 | return page; 23 | } 24 | } 25 | -------------------------------------------------------------------------------- /src/AbstractFactory/A2/factory/Item.java: -------------------------------------------------------------------------------- 1 | package factory; 2 | 3 | public abstract class Item { 4 | protected String caption; 5 | public Item(String caption) { 6 | this.caption = caption; 7 | } 8 | public abstract String makeHTML(); 9 | } 10 | -------------------------------------------------------------------------------- /src/AbstractFactory/A2/factory/Link.java: -------------------------------------------------------------------------------- 1 | package factory; 2 | 3 | public abstract class Link extends Item { 4 | protected String url; 5 | public Link(String caption, String url) { 6 | super(caption); 7 | this.url = url; 8 | } 9 | } 10 | -------------------------------------------------------------------------------- /src/AbstractFactory/A2/factory/Page.java: -------------------------------------------------------------------------------- 1 | package factory; 2 | import java.io.*; 3 | import java.util.*; 4 | 5 | public abstract class Page { 6 | protected String title; 7 | protected String author; 8 | protected ArrayList content = new ArrayList(); 9 | public Page(String title, String author) { 10 | this.title = title; 11 | this.author = author; 12 | } 13 | public void add(Item item) { 14 | content.add(item); 15 | } 16 | public void output() { 17 | try { 18 | String filename = title + ".html"; 19 | Writer writer = new FileWriter(filename); 20 | writer.write(this.makeHTML()); 21 | writer.close(); 22 | System.out.println(filename + " 编写完成。"); 23 | } catch (IOException e) { 24 | e.printStackTrace(); 25 | } 26 | } 27 | public abstract String makeHTML(); 28 | } 29 | -------------------------------------------------------------------------------- /src/AbstractFactory/A2/factory/Tray.java: -------------------------------------------------------------------------------- 1 | package factory; 2 | import java.util.ArrayList; 3 | 4 | public abstract class Tray extends Item { 5 | protected ArrayList tray = new ArrayList(); 6 | public Tray(String caption) { 7 | super(caption); 8 | } 9 | public void add(Item item) { 10 | tray.add(item); 11 | } 12 | } 13 | -------------------------------------------------------------------------------- /src/AbstractFactory/A2/listfactory/ListFactory.java: -------------------------------------------------------------------------------- 1 | package listfactory; 2 | import factory.*; 3 | 4 | public class ListFactory extends Factory { 5 | public Link createLink(String caption, String url) { 6 | return new ListLink(caption, url); 7 | } 8 | public Tray createTray(String caption) { 9 | return new ListTray(caption); 10 | } 11 | public Page createPage(String title, String author) { 12 | return new ListPage(title, author); 13 | } 14 | } 15 | -------------------------------------------------------------------------------- /src/AbstractFactory/A2/listfactory/ListLink.java: -------------------------------------------------------------------------------- 1 | package listfactory; 2 | import factory.*; 3 | 4 | public class ListLink extends Link { 5 | public ListLink(String caption, String url) { 6 | super(caption, url); 7 | } 8 | public String makeHTML() { 9 | return "
  • " + caption + "
  • \n"; 10 | } 11 | } 12 | -------------------------------------------------------------------------------- /src/AbstractFactory/A2/listfactory/ListPage.java: -------------------------------------------------------------------------------- 1 | package listfactory; 2 | import factory.*; 3 | import java.util.Iterator; 4 | 5 | public class ListPage extends Page { 6 | public ListPage(String title, String author) { 7 | super(title, author); 8 | } 9 | public String makeHTML() { 10 | StringBuffer buffer = new StringBuffer(); 11 | buffer.append("" + title + "\n"); 12 | buffer.append("\n"); 13 | buffer.append("

    " + title + "

    \n"); 14 | buffer.append("\n"); 21 | buffer.append("
    " + author + "
    "); 22 | buffer.append("\n"); 23 | return buffer.toString(); 24 | } 25 | } 26 | -------------------------------------------------------------------------------- /src/AbstractFactory/A2/listfactory/ListTray.java: -------------------------------------------------------------------------------- 1 | package listfactory; 2 | import factory.*; 3 | import java.util.Iterator; 4 | 5 | public class ListTray extends Tray { 6 | public ListTray(String caption) { 7 | super(caption); 8 | } 9 | public String makeHTML() { 10 | StringBuffer buffer = new StringBuffer(); 11 | buffer.append("
  • \n"); 12 | buffer.append(caption + "\n"); 13 | buffer.append("\n"); 20 | buffer.append("
  • \n"); 21 | return buffer.toString(); 22 | } 23 | } 24 | -------------------------------------------------------------------------------- /src/AbstractFactory/A2/tablefactory/TableFactory.java: -------------------------------------------------------------------------------- 1 | package tablefactory; 2 | import factory.*; 3 | 4 | public class TableFactory extends Factory { 5 | public Link createLink(String caption, String url) { 6 | return new TableLink(caption, url); 7 | } 8 | public Tray createTray(String caption) { 9 | return new TableTray(caption); 10 | } 11 | public Page createPage(String title, String author) { 12 | return new TablePage(title, author); 13 | } 14 | } 15 | -------------------------------------------------------------------------------- /src/AbstractFactory/A2/tablefactory/TableLink.java: -------------------------------------------------------------------------------- 1 | package tablefactory; 2 | import factory.*; 3 | 4 | public class TableLink extends Link { 5 | public TableLink(String caption, String url) { 6 | super(caption, url); 7 | } 8 | public String makeHTML() { 9 | return "" + caption + "\n"; 10 | } 11 | } 12 | -------------------------------------------------------------------------------- /src/AbstractFactory/A2/tablefactory/TablePage.java: -------------------------------------------------------------------------------- 1 | package tablefactory; 2 | import factory.*; 3 | import java.util.Iterator; 4 | 5 | public class TablePage extends Page { 6 | public TablePage(String title, String author) { 7 | super(title, author); 8 | } 9 | public String makeHTML() { 10 | StringBuffer buffer = new StringBuffer(); 11 | buffer.append("" + title + "\n"); 12 | buffer.append("\n"); 13 | buffer.append("

    " + title + "

    \n"); 14 | buffer.append("\n"); 15 | Iterator it = content.iterator(); 16 | while (it.hasNext()) { 17 | Item item = (Item)it.next(); 18 | buffer.append("" + item.makeHTML() + ""); 19 | } 20 | buffer.append("
    \n"); 21 | buffer.append("
    " + author + "
    "); 22 | buffer.append("\n"); 23 | return buffer.toString(); 24 | } 25 | } 26 | -------------------------------------------------------------------------------- /src/AbstractFactory/A2/tablefactory/TableTray.java: -------------------------------------------------------------------------------- 1 | package tablefactory; 2 | import factory.*; 3 | import java.util.Iterator; 4 | 5 | public class TableTray extends Tray { 6 | public TableTray(String caption) { 7 | super(caption); // 使用super(...)表达式 8 | } 9 | public String makeHTML() { 10 | StringBuffer buffer = new StringBuffer(); 11 | buffer.append(""); 12 | buffer.append(""); 13 | buffer.append(""); 14 | buffer.append("\n"); 15 | buffer.append("\n"); 16 | Iterator it = tray.iterator(); 17 | while (it.hasNext()) { 18 | Item item = (Item)it.next(); 19 | buffer.append(item.makeHTML()); 20 | } 21 | buffer.append("
    " + caption + "
    "); 22 | buffer.append(""); 23 | return buffer.toString(); 24 | } 25 | } 26 | -------------------------------------------------------------------------------- /src/AbstractFactory/Sample/factory/Factory.java: -------------------------------------------------------------------------------- 1 | package factory; 2 | 3 | public abstract class Factory { 4 | public static Factory getFactory(String classname) { 5 | Factory factory = null; 6 | try { 7 | factory = (Factory)Class.forName(classname).newInstance(); 8 | } catch (ClassNotFoundException e) { 9 | System.err.println("没有找到 " + classname + "类。"); 10 | } catch (Exception e) { 11 | e.printStackTrace(); 12 | } 13 | return factory; 14 | } 15 | public abstract Link createLink(String caption, String url); 16 | public abstract Tray createTray(String caption); 17 | public abstract Page createPage(String title, String author); 18 | } 19 | -------------------------------------------------------------------------------- /src/AbstractFactory/Sample/factory/Item.java: -------------------------------------------------------------------------------- 1 | package factory; 2 | 3 | public abstract class Item { 4 | protected String caption; 5 | public Item(String caption) { 6 | this.caption = caption; 7 | } 8 | public abstract String makeHTML(); 9 | } 10 | -------------------------------------------------------------------------------- /src/AbstractFactory/Sample/factory/Link.java: -------------------------------------------------------------------------------- 1 | package factory; 2 | 3 | public abstract class Link extends Item { 4 | protected String url; 5 | public Link(String caption, String url) { 6 | super(caption); 7 | this.url = url; 8 | } 9 | } 10 | -------------------------------------------------------------------------------- /src/AbstractFactory/Sample/factory/Page.java: -------------------------------------------------------------------------------- 1 | package factory; 2 | import java.io.*; 3 | import java.util.ArrayList; 4 | 5 | public abstract class Page { 6 | protected String title; 7 | protected String author; 8 | protected ArrayList content = new ArrayList(); 9 | public Page(String title, String author) { 10 | this.title = title; 11 | this.author = author; 12 | } 13 | public void add(Item item) { 14 | content.add(item); 15 | } 16 | public void output() { 17 | try { 18 | String filename = title + ".html"; 19 | Writer writer = new FileWriter(filename); 20 | writer.write(this.makeHTML()); 21 | writer.close(); 22 | System.out.println(filename + " 编写完成。"); 23 | } catch (IOException e) { 24 | e.printStackTrace(); 25 | } 26 | } 27 | public abstract String makeHTML(); 28 | } 29 | -------------------------------------------------------------------------------- /src/AbstractFactory/Sample/factory/Tray.java: -------------------------------------------------------------------------------- 1 | package factory; 2 | import java.util.ArrayList; 3 | 4 | public abstract class Tray extends Item { 5 | protected ArrayList tray = new ArrayList(); 6 | public Tray(String caption) { 7 | super(caption); 8 | } 9 | public void add(Item item) { 10 | tray.add(item); 11 | } 12 | } 13 | -------------------------------------------------------------------------------- /src/AbstractFactory/Sample/listfactory/ListFactory.java: -------------------------------------------------------------------------------- 1 | package listfactory; 2 | import factory.*; 3 | 4 | public class ListFactory extends Factory { 5 | public Link createLink(String caption, String url) { 6 | return new ListLink(caption, url); 7 | } 8 | public Tray createTray(String caption) { 9 | return new ListTray(caption); 10 | } 11 | public Page createPage(String title, String author) { 12 | return new ListPage(title, author); 13 | } 14 | } 15 | -------------------------------------------------------------------------------- /src/AbstractFactory/Sample/listfactory/ListLink.java: -------------------------------------------------------------------------------- 1 | package listfactory; 2 | import factory.*; 3 | 4 | public class ListLink extends Link { 5 | public ListLink(String caption, String url) { 6 | super(caption, url); 7 | } 8 | public String makeHTML() { 9 | return "
  • " + caption + "
  • \n"; 10 | } 11 | } 12 | -------------------------------------------------------------------------------- /src/AbstractFactory/Sample/listfactory/ListPage.java: -------------------------------------------------------------------------------- 1 | package listfactory; 2 | import factory.*; 3 | import java.util.Iterator; 4 | 5 | public class ListPage extends Page { 6 | public ListPage(String title, String author) { 7 | super(title, author); 8 | } 9 | public String makeHTML() { 10 | StringBuffer buffer = new StringBuffer(); 11 | buffer.append("" + title + "\n"); 12 | buffer.append("\n"); 13 | buffer.append("

    " + title + "

    \n"); 14 | buffer.append("\n"); 21 | buffer.append("
    " + author + "
    "); 22 | buffer.append("\n"); 23 | return buffer.toString(); 24 | } 25 | } 26 | -------------------------------------------------------------------------------- /src/AbstractFactory/Sample/listfactory/ListTray.java: -------------------------------------------------------------------------------- 1 | package listfactory; 2 | import factory.*; 3 | import java.util.Iterator; 4 | 5 | public class ListTray extends Tray { 6 | public ListTray(String caption) { 7 | super(caption); 8 | } 9 | public String makeHTML() { 10 | StringBuffer buffer = new StringBuffer(); 11 | buffer.append("
  • \n"); 12 | buffer.append(caption + "\n"); 13 | buffer.append("\n"); 20 | buffer.append("
  • \n"); 21 | return buffer.toString(); 22 | } 23 | } 24 | -------------------------------------------------------------------------------- /src/AbstractFactory/Sample/tablefactory/TableFactory.java: -------------------------------------------------------------------------------- 1 | package tablefactory; 2 | import factory.*; 3 | 4 | public class TableFactory extends Factory { 5 | public Link createLink(String caption, String url) { 6 | return new TableLink(caption, url); 7 | } 8 | public Tray createTray(String caption) { 9 | return new TableTray(caption); 10 | } 11 | public Page createPage(String title, String author) { 12 | return new TablePage(title, author); 13 | } 14 | } 15 | -------------------------------------------------------------------------------- /src/AbstractFactory/Sample/tablefactory/TableLink.java: -------------------------------------------------------------------------------- 1 | package tablefactory; 2 | import factory.*; 3 | 4 | public class TableLink extends Link { 5 | public TableLink(String caption, String url) { 6 | super(caption, url); 7 | } 8 | public String makeHTML() { 9 | return "" + caption + "\n"; 10 | } 11 | } 12 | -------------------------------------------------------------------------------- /src/AbstractFactory/Sample/tablefactory/TablePage.java: -------------------------------------------------------------------------------- 1 | package tablefactory; 2 | import factory.*; 3 | import java.util.Iterator; 4 | 5 | public class TablePage extends Page { 6 | public TablePage(String title, String author) { 7 | super(title, author); 8 | } 9 | public String makeHTML() { 10 | StringBuffer buffer = new StringBuffer(); 11 | buffer.append("" + title + "\n"); 12 | buffer.append("\n"); 13 | buffer.append("

    " + title + "

    \n"); 14 | buffer.append("\n"); 15 | Iterator it = content.iterator(); 16 | while (it.hasNext()) { 17 | Item item = (Item)it.next(); 18 | buffer.append("" + item.makeHTML() + ""); 19 | } 20 | buffer.append("
    \n"); 21 | buffer.append("
    " + author + "
    "); 22 | buffer.append("\n"); 23 | return buffer.toString(); 24 | } 25 | } 26 | -------------------------------------------------------------------------------- /src/AbstractFactory/Sample/tablefactory/TableTray.java: -------------------------------------------------------------------------------- 1 | package tablefactory; 2 | import factory.*; 3 | import java.util.Iterator; 4 | 5 | public class TableTray extends Tray { 6 | public TableTray(String caption) { 7 | super(caption); // 使用super(...)表达式 8 | } 9 | public String makeHTML() { 10 | StringBuffer buffer = new StringBuffer(); 11 | buffer.append(""); 12 | buffer.append(""); 13 | buffer.append(""); 14 | buffer.append("\n"); 15 | buffer.append("\n"); 16 | Iterator it = tray.iterator(); 17 | while (it.hasNext()) { 18 | Item item = (Item)it.next(); 19 | buffer.append(item.makeHTML()); 20 | } 21 | buffer.append("
    " + caption + "
    "); 22 | buffer.append(""); 23 | return buffer.toString(); 24 | } 25 | } 26 | -------------------------------------------------------------------------------- /src/Adapter/A2/FileIO.java: -------------------------------------------------------------------------------- 1 | import java.io.*; 2 | 3 | public interface FileIO { 4 | public void readFromFile(String filename) throws IOException; 5 | public void writeToFile(String filename) throws IOException; 6 | public void setValue(String key, String value); 7 | public String getValue(String key); 8 | } 9 | -------------------------------------------------------------------------------- /src/Adapter/A2/FileProperties.java: -------------------------------------------------------------------------------- 1 | import java.io.*; 2 | import java.util.*; 3 | 4 | public class FileProperties extends Properties implements FileIO { 5 | public void readFromFile(String filename) throws IOException { 6 | load(new FileInputStream(filename)); 7 | } 8 | public void writeToFile(String filename) throws IOException { 9 | store(new FileOutputStream(filename), "written by FileProperties"); 10 | } 11 | public void setValue(String key, String value) { 12 | setProperty(key, value); 13 | } 14 | public String getValue(String key) { 15 | return getProperty(key, ""); 16 | } 17 | } 18 | -------------------------------------------------------------------------------- /src/Adapter/A2/Main.java: -------------------------------------------------------------------------------- 1 | import java.io.*; 2 | 3 | public class Main { 4 | public static void main(String[] args) { 5 | FileIO f = new FileProperties(); 6 | try { 7 | f.readFromFile("file.txt"); 8 | f.setValue("year", "2004"); 9 | f.setValue("month", "4"); 10 | f.setValue("day", "21"); 11 | f.writeToFile("newfile.txt"); 12 | } catch (IOException e) { 13 | e.printStackTrace(); 14 | } 15 | } 16 | } 17 | -------------------------------------------------------------------------------- /src/Adapter/A2/file.txt: -------------------------------------------------------------------------------- 1 | year=1999 2 | -------------------------------------------------------------------------------- /src/Adapter/Q2/FileIO.java: -------------------------------------------------------------------------------- 1 | import java.io.*; 2 | 3 | public interface FileIO { 4 | public void readFromFile(String filename) throws IOException; 5 | public void writeToFile(String filename) throws IOException; 6 | public void setValue(String key, String value); 7 | public String getValue(String key); 8 | } 9 | -------------------------------------------------------------------------------- /src/Adapter/Q2/Main.java: -------------------------------------------------------------------------------- 1 | import java.io.*; 2 | 3 | public class Main { 4 | public static void main(String[] args) { 5 | FileIO f = new FileProperties(); 6 | try { 7 | f.readFromFile("file.txt"); 8 | f.setValue("year", "2004"); 9 | f.setValue("month", "4"); 10 | f.setValue("day", "21"); 11 | f.writeToFile("newfile.txt"); 12 | } catch (IOException e) { 13 | e.printStackTrace(); 14 | } 15 | } 16 | } 17 | -------------------------------------------------------------------------------- /src/Adapter/Q2/file.txt: -------------------------------------------------------------------------------- 1 | year=1999 2 | -------------------------------------------------------------------------------- /src/Adapter/Q2/newfile.txt: -------------------------------------------------------------------------------- 1 | #written by FileProperties 2 | #Mon Nov 20 10:27:07 JST 2000 3 | day=20 4 | year=2000 5 | month=11 6 | -------------------------------------------------------------------------------- /src/Adapter/Sample1/Banner.java: -------------------------------------------------------------------------------- 1 | public class Banner { 2 | private String string; 3 | public Banner(String string) { 4 | this.string = string; 5 | } 6 | public void showWithParen() { 7 | System.out.println("(" + string + ")"); 8 | } 9 | public void showWithAster() { 10 | System.out.println("*" + string + "*"); 11 | } 12 | } 13 | -------------------------------------------------------------------------------- /src/Adapter/Sample1/Main.java: -------------------------------------------------------------------------------- 1 | public class Main { 2 | public static void main(String[] args) { 3 | Print p = new PrintBanner("Hello"); 4 | p.printWeak(); 5 | p.printStrong(); 6 | } 7 | } 8 | -------------------------------------------------------------------------------- /src/Adapter/Sample1/Print.java: -------------------------------------------------------------------------------- 1 | public interface Print { 2 | public abstract void printWeak(); 3 | public abstract void printStrong(); 4 | } 5 | -------------------------------------------------------------------------------- /src/Adapter/Sample1/PrintBanner.java: -------------------------------------------------------------------------------- 1 | public class PrintBanner extends Banner implements Print { 2 | public PrintBanner(String string) { 3 | super(string); 4 | } 5 | public void printWeak() { 6 | showWithParen(); 7 | } 8 | public void printStrong() { 9 | showWithAster(); 10 | } 11 | } 12 | -------------------------------------------------------------------------------- /src/Adapter/Sample2/Banner.java: -------------------------------------------------------------------------------- 1 | public class Banner { 2 | private String string; 3 | public Banner(String string) { 4 | this.string = string; 5 | } 6 | public void showWithParen() { 7 | System.out.println("(" + string + ")"); 8 | } 9 | public void showWithAster() { 10 | System.out.println("*" + string + "*"); 11 | } 12 | } 13 | -------------------------------------------------------------------------------- /src/Adapter/Sample2/Main.java: -------------------------------------------------------------------------------- 1 | public class Main { 2 | public static void main(String[] args) { 3 | Print p = new PrintBanner("Hello"); 4 | p.printWeak(); 5 | p.printStrong(); 6 | } 7 | } 8 | -------------------------------------------------------------------------------- /src/Adapter/Sample2/Print.java: -------------------------------------------------------------------------------- 1 | public abstract class Print { 2 | public abstract void printWeak(); 3 | public abstract void printStrong(); 4 | } 5 | -------------------------------------------------------------------------------- /src/Adapter/Sample2/PrintBanner.java: -------------------------------------------------------------------------------- 1 | public class PrintBanner extends Print { 2 | private Banner banner; 3 | public PrintBanner(String string) { 4 | this.banner = new Banner(string); 5 | } 6 | public void printWeak() { 7 | banner.showWithParen(); 8 | } 9 | public void printStrong() { 10 | banner.showWithAster(); 11 | } 12 | } 13 | -------------------------------------------------------------------------------- /src/Bridge/A1/CountDisplay.java: -------------------------------------------------------------------------------- 1 | public class CountDisplay extends Display { 2 | public CountDisplay(DisplayImpl impl) { 3 | super(impl); 4 | } 5 | public void multiDisplay(int times) { // 循环显示times次 6 | open(); 7 | for (int i = 0; i < times; i++) { 8 | print(); 9 | } 10 | close(); 11 | } 12 | } 13 | -------------------------------------------------------------------------------- /src/Bridge/A1/Display.java: -------------------------------------------------------------------------------- 1 | public class Display { 2 | private DisplayImpl impl; 3 | public Display(DisplayImpl impl) { 4 | this.impl = impl; 5 | } 6 | public void open() { 7 | impl.rawOpen(); 8 | } 9 | public void print() { 10 | impl.rawPrint(); 11 | } 12 | public void close() { 13 | impl.rawClose(); 14 | } 15 | public final void display() { 16 | open(); 17 | print(); 18 | close(); 19 | } 20 | } 21 | -------------------------------------------------------------------------------- /src/Bridge/A1/DisplayImpl.java: -------------------------------------------------------------------------------- 1 | public abstract class DisplayImpl { 2 | public abstract void rawOpen(); 3 | public abstract void rawPrint(); 4 | public abstract void rawClose(); 5 | } 6 | -------------------------------------------------------------------------------- /src/Bridge/A1/Main.java: -------------------------------------------------------------------------------- 1 | public class Main { 2 | public static void main(String[] args) { 3 | RandomCountDisplay d = new RandomCountDisplay(new StringDisplayImpl("Hello, China.")); 4 | d.randomDisplay(10); 5 | } 6 | } 7 | -------------------------------------------------------------------------------- /src/Bridge/A1/RandomCountDisplay.java: -------------------------------------------------------------------------------- 1 | import java.util.Random; 2 | 3 | public class RandomCountDisplay extends CountDisplay { 4 | private Random random = new Random(); 5 | public RandomCountDisplay(DisplayImpl impl) { 6 | super(impl); 7 | } 8 | public void randomDisplay(int times) { 9 | multiDisplay(random.nextInt(times)); 10 | } 11 | } 12 | -------------------------------------------------------------------------------- /src/Bridge/A1/StringDisplayImpl.java: -------------------------------------------------------------------------------- 1 | public class StringDisplayImpl extends DisplayImpl { 2 | private String string; // 要显示的字符串 3 | private int width; // 以字节单位计算出的字符串的宽度 4 | public StringDisplayImpl(String string) { // 构造函数接收要显示的字符串string 5 | this.string = string; // 将它保存在字段中 6 | this.width = string.getBytes().length; // 把字符串的宽度也保存在字段中,以供使用。 7 | } 8 | public void rawOpen() { 9 | printLine(); 10 | } 11 | public void rawPrint() { 12 | System.out.println("|" + string + "|"); // 前后加上"|"并显示 13 | } 14 | public void rawClose() { 15 | printLine(); 16 | } 17 | private void printLine() { 18 | System.out.print("+"); // 显示用来表示方框的角的"+" 19 | for (int i = 0; i < width; i++) { // 显示width个"-" 20 | System.out.print("-"); // 将其用作方框的边框 21 | } 22 | System.out.println("+"); // 显示用来表示方框的角的"+" 23 | } 24 | } 25 | -------------------------------------------------------------------------------- /src/Bridge/A2/CountDisplay.java: -------------------------------------------------------------------------------- 1 | public class CountDisplay extends Display { 2 | public CountDisplay(DisplayImpl impl) { 3 | super(impl); 4 | } 5 | public void multiDisplay(int times) { // 循环显示times次 6 | open(); 7 | for (int i = 0; i < times; i++) { 8 | print(); 9 | } 10 | close(); 11 | } 12 | } 13 | -------------------------------------------------------------------------------- /src/Bridge/A2/Display.java: -------------------------------------------------------------------------------- 1 | public class Display { 2 | private DisplayImpl impl; 3 | public Display(DisplayImpl impl) { 4 | this.impl = impl; 5 | } 6 | public void open() { 7 | impl.rawOpen(); 8 | } 9 | public void print() { 10 | impl.rawPrint(); 11 | } 12 | public void close() { 13 | impl.rawClose(); 14 | } 15 | public final void display() { 16 | open(); 17 | print(); 18 | close(); 19 | } 20 | } 21 | -------------------------------------------------------------------------------- /src/Bridge/A2/DisplayImpl.java: -------------------------------------------------------------------------------- 1 | public abstract class DisplayImpl { 2 | public abstract void rawOpen(); 3 | public abstract void rawPrint(); 4 | public abstract void rawClose(); 5 | } 6 | -------------------------------------------------------------------------------- /src/Bridge/A2/Main.java: -------------------------------------------------------------------------------- 1 | public class Main { 2 | public static void main(String[] args) { 3 | CountDisplay d = new CountDisplay(new FileDisplayImpl("star.txt")); 4 | d.multiDisplay(3); 5 | } 6 | } 7 | -------------------------------------------------------------------------------- /src/Bridge/A2/RandomCountDisplay.java: -------------------------------------------------------------------------------- 1 | import java.util.Random; 2 | 3 | public class RandomCountDisplay extends CountDisplay { 4 | private Random random = new Random(); 5 | public RandomCountDisplay(DisplayImpl impl) { 6 | super(impl); 7 | } 8 | public void randomDisplay(int times) { 9 | multiDisplay(random.nextInt(times)); 10 | } 11 | } 12 | -------------------------------------------------------------------------------- /src/Bridge/A2/StringDisplayImpl.java: -------------------------------------------------------------------------------- 1 | public class StringDisplayImpl extends DisplayImpl { 2 | private String string; // 要显示的字符串 3 | private int width; // 以字节单位计算出的字符串的宽度 4 | public StringDisplayImpl(String string) { // 构造函数接收要显示的字符串string 5 | this.string = string; // 将它保存在字段中 6 | this.width = string.getBytes().length; // 把字符串的宽度也保存在字段中,以供使用。 7 | } 8 | public void rawOpen() { 9 | printLine(); 10 | } 11 | public void rawPrint() { 12 | System.out.println("|" + string + "|"); // 前后加上"|"并显示 13 | } 14 | public void rawClose() { 15 | printLine(); 16 | } 17 | private void printLine() { 18 | System.out.print("+"); // 显示用来表示方框的角的"+" 19 | for (int i = 0; i < width; i++) { // 显示width个"-" 20 | System.out.print("-"); // 将其用作方框的边框 21 | } 22 | System.out.println("+"); // 显示用来表示方框的角的"+" 23 | } 24 | } 25 | -------------------------------------------------------------------------------- /src/Bridge/A2/star.txt: -------------------------------------------------------------------------------- 1 | Twinkle, twinkle, little star, 2 | How I wonder what you are. 3 | -------------------------------------------------------------------------------- /src/Bridge/A3/CharDisplayImpl.java: -------------------------------------------------------------------------------- 1 | public class CharDisplayImpl extends DisplayImpl { 2 | private char head; 3 | private char body; 4 | private char foot; 5 | public CharDisplayImpl(char head, char body, char foot) { 6 | this.head = head; 7 | this.body = body; 8 | this.foot = foot; 9 | } 10 | public void rawOpen() { 11 | System.out.print(head); 12 | } 13 | public void rawPrint() { 14 | System.out.print(body); 15 | } 16 | public void rawClose() { 17 | System.out.println(foot); 18 | } 19 | } 20 | -------------------------------------------------------------------------------- /src/Bridge/A3/CountDisplay.java: -------------------------------------------------------------------------------- 1 | public class CountDisplay extends Display { 2 | public CountDisplay(DisplayImpl impl) { 3 | super(impl); 4 | } 5 | public void multiDisplay(int times) { // 循环显示times次 6 | open(); 7 | for (int i = 0; i < times; i++) { 8 | print(); 9 | } 10 | close(); 11 | } 12 | } 13 | -------------------------------------------------------------------------------- /src/Bridge/A3/Display.java: -------------------------------------------------------------------------------- 1 | public class Display { 2 | private DisplayImpl impl; 3 | public Display(DisplayImpl impl) { 4 | this.impl = impl; 5 | } 6 | public void open() { 7 | impl.rawOpen(); 8 | } 9 | public void print() { 10 | impl.rawPrint(); 11 | } 12 | public void close() { 13 | impl.rawClose(); 14 | } 15 | public final void display() { 16 | open(); 17 | print(); 18 | close(); 19 | } 20 | } 21 | -------------------------------------------------------------------------------- /src/Bridge/A3/DisplayImpl.java: -------------------------------------------------------------------------------- 1 | public abstract class DisplayImpl { 2 | public abstract void rawOpen(); 3 | public abstract void rawPrint(); 4 | public abstract void rawClose(); 5 | } 6 | -------------------------------------------------------------------------------- /src/Bridge/A3/IncreaseDisplay.java: -------------------------------------------------------------------------------- 1 | public class IncreaseDisplay extends CountDisplay { 2 | private int step; // 递增步长 3 | public IncreaseDisplay(DisplayImpl impl, int step) { 4 | super(impl); 5 | this.step = step; 6 | } 7 | public void increaseDisplay(int level) { 8 | int count = 0; 9 | for (int i = 0; i < level; i++) { 10 | multiDisplay(count); 11 | count += step; 12 | } 13 | } 14 | } 15 | -------------------------------------------------------------------------------- /src/Bridge/A3/Main.java: -------------------------------------------------------------------------------- 1 | public class Main { 2 | public static void main(String[] args) { 3 | IncreaseDisplay d1 = new IncreaseDisplay(new CharDisplayImpl('<', '*', '>'), 1); 4 | IncreaseDisplay d2 = new IncreaseDisplay(new CharDisplayImpl('|', '#', '-'), 2); 5 | d1.increaseDisplay(4); 6 | d2.increaseDisplay(6); 7 | } 8 | } 9 | -------------------------------------------------------------------------------- /src/Bridge/A3/StringDisplayImpl.java: -------------------------------------------------------------------------------- 1 | public class StringDisplayImpl extends DisplayImpl { 2 | private String string; // 要显示的字符串 3 | private int width; // 以字节单位计算出的字符串的宽度 4 | public StringDisplayImpl(String string) { // 构造函数接收要显示的字符串string 5 | this.string = string; // 将它保存在字段中 6 | this.width = string.getBytes().length; // 把字符串的宽度也保存在字段中,以供使用。 7 | } 8 | public void rawOpen() { 9 | printLine(); 10 | } 11 | public void rawPrint() { 12 | System.out.println("|" + string + "|"); // 前后加上"|"并显示 13 | } 14 | public void rawClose() { 15 | printLine(); 16 | } 17 | private void printLine() { 18 | System.out.print("+"); // 显示用来表示方框的角的"+" 19 | for (int i = 0; i < width; i++) { // 显示width个"-" 20 | System.out.print("-"); // 将其用作方框的边框 21 | } 22 | System.out.println("+"); // 显示用来表示方框的角的"+" 23 | } 24 | } 25 | -------------------------------------------------------------------------------- /src/Bridge/Sample/CountDisplay.java: -------------------------------------------------------------------------------- 1 | public class CountDisplay extends Display { 2 | public CountDisplay(DisplayImpl impl) { 3 | super(impl); 4 | } 5 | public void multiDisplay(int times) { // 循环显示times次 6 | open(); 7 | for (int i = 0; i < times; i++) { 8 | print(); 9 | } 10 | close(); 11 | } 12 | } 13 | -------------------------------------------------------------------------------- /src/Bridge/Sample/Display.java: -------------------------------------------------------------------------------- 1 | public class Display { 2 | private DisplayImpl impl; 3 | public Display(DisplayImpl impl) { 4 | this.impl = impl; 5 | } 6 | public void open() { 7 | impl.rawOpen(); 8 | } 9 | public void print() { 10 | impl.rawPrint(); 11 | } 12 | public void close() { 13 | impl.rawClose(); 14 | } 15 | public final void display() { 16 | open(); 17 | print(); 18 | close(); 19 | } 20 | } 21 | -------------------------------------------------------------------------------- /src/Bridge/Sample/DisplayImpl.java: -------------------------------------------------------------------------------- 1 | public abstract class DisplayImpl { 2 | public abstract void rawOpen(); 3 | public abstract void rawPrint(); 4 | public abstract void rawClose(); 5 | } 6 | -------------------------------------------------------------------------------- /src/Bridge/Sample/Main.java: -------------------------------------------------------------------------------- 1 | public class Main { 2 | public static void main(String[] args) { 3 | Display d1 = new Display(new StringDisplayImpl("Hello, China.")); 4 | Display d2 = new CountDisplay(new StringDisplayImpl("Hello, World.")); 5 | CountDisplay d3 = new CountDisplay(new StringDisplayImpl("Hello, Universe.")); 6 | d1.display(); 7 | d2.display(); 8 | d3.display(); 9 | d3.multiDisplay(5); 10 | } 11 | } 12 | -------------------------------------------------------------------------------- /src/Bridge/Sample/StringDisplayImpl.java: -------------------------------------------------------------------------------- 1 | public class StringDisplayImpl extends DisplayImpl { 2 | private String string; // 要显示的字符串 3 | private int width; // 以字节单位计算出的字符串的宽度 4 | public StringDisplayImpl(String string) { // 构造函数接收要显示的字符串string 5 | this.string = string; // 将它保存在字段中 6 | this.width = string.getBytes().length; // 把字符串的宽度也保存在字段中,以供使用。 7 | } 8 | public void rawOpen() { 9 | printLine(); 10 | } 11 | public void rawPrint() { 12 | System.out.println("|" + string + "|"); // 前后加上"|"并显示 13 | } 14 | public void rawClose() { 15 | printLine(); 16 | } 17 | private void printLine() { 18 | System.out.print("+"); // 显示用来表示方框的角的"+" 19 | for (int i = 0; i < width; i++) { // 显示width个"-" 20 | System.out.print("-"); // 将其用作方框的边框 21 | } 22 | System.out.println("+"); // 显示用来表示方框的角的"+" 23 | } 24 | } 25 | -------------------------------------------------------------------------------- /src/Builder/A2/Builder.java: -------------------------------------------------------------------------------- 1 | public abstract class Builder { 2 | private boolean initialized = false; 3 | public void makeTitle(String title) { 4 | if (!initialized) { 5 | buildTitle(title); 6 | initialized = true; 7 | } 8 | } 9 | public void makeString(String str) { 10 | if (initialized) { 11 | buildString(str); 12 | } 13 | } 14 | public void makeItems(String[] items) { 15 | if (initialized) { 16 | buildItems(items); 17 | } 18 | } 19 | public void close() { 20 | if (initialized) { 21 | buildDone(); 22 | } 23 | } 24 | protected abstract void buildTitle(String title); 25 | protected abstract void buildString(String str); 26 | protected abstract void buildItems(String[] items); 27 | protected abstract void buildDone(); 28 | } 29 | -------------------------------------------------------------------------------- /src/Builder/A2/Director.java: -------------------------------------------------------------------------------- 1 | public class Director { 2 | private Builder builder; 3 | public Director(Builder builder) { // 因为接收的参数是Builder类的子类 4 | this.builder = builder; // 所以可以将其保存在builder字段中 5 | } 6 | public void construct() { // 编写文档 7 | builder.makeTitle("Greeting"); // 标题 8 | builder.makeString("从早上至下午"); // 字符串 9 | builder.makeItems(new String[]{ // 条目 10 | "早上好。", 11 | "下午好。", 12 | }); 13 | builder.makeString("晚上"); // 其他字符串 14 | builder.makeItems(new String[]{ // 其他条目 15 | "晚上好。", 16 | "晚安。", 17 | "再见。", 18 | }); 19 | builder.close(); // 完成文档 20 | } 21 | } 22 | -------------------------------------------------------------------------------- /src/Builder/A2/Main.java: -------------------------------------------------------------------------------- 1 | public class Main { 2 | public static void main(String[] args) { 3 | if (args.length != 1) { 4 | usage(); 5 | System.exit(0); 6 | } 7 | if (args[0].equals("plain")) { 8 | TextBuilder textbuilder = new TextBuilder(); 9 | Director director = new Director(textbuilder); 10 | director.construct(); 11 | String result = textbuilder.getResult(); 12 | System.out.println(result); 13 | } else if (args[0].equals("html")) { 14 | HTMLBuilder htmlbuilder = new HTMLBuilder(); 15 | Director director = new Director(htmlbuilder); 16 | director.construct(); 17 | String filename = htmlbuilder.getResult(); 18 | System.out.println(filename + "文件编写完成。"); 19 | } else { 20 | usage(); 21 | System.exit(0); 22 | } 23 | } 24 | public static void usage() { 25 | System.out.println("Usage: java Main plain 编写纯文本文档"); 26 | System.out.println("Usage: java Main html 编写HTML文档"); 27 | } 28 | } 29 | -------------------------------------------------------------------------------- /src/Builder/A3/Builder.java: -------------------------------------------------------------------------------- 1 | public abstract class Builder { 2 | public abstract void makeTitle(String title); 3 | public abstract void makeString(String str); 4 | public abstract void makeItems(String[] items); 5 | public abstract void close(); 6 | } 7 | -------------------------------------------------------------------------------- /src/Builder/A3/Director.java: -------------------------------------------------------------------------------- 1 | public class Director { 2 | private Builder builder; 3 | public Director(Builder builder) { // 因为接收的参数是Builder类的子类 4 | this.builder = builder; // 所以可以将其保存在builder字段中 5 | } 6 | public void construct() { // 编写文档 7 | builder.makeTitle("Greeting"); // 标题 8 | builder.makeString("从早上至下午"); // 字符串 9 | builder.makeItems(new String[]{ // 条目 10 | "早上好。", 11 | "下午好。", 12 | }); 13 | builder.makeString("晚上"); // 其他字符串 14 | builder.makeItems(new String[]{ // 其他条目 15 | "晚上好。", 16 | "晚安。", 17 | "再见。", 18 | }); 19 | builder.close(); // 完成文档 20 | } 21 | } 22 | -------------------------------------------------------------------------------- /src/Builder/A3/Main.java: -------------------------------------------------------------------------------- 1 | import javax.swing.*; 2 | 3 | public class Main { 4 | public static void main(String[] args) { 5 | FrameBuilder framebuilder = new FrameBuilder(); 6 | Director director = new Director(framebuilder); 7 | director.construct(); 8 | JFrame frame = framebuilder.getResult(); 9 | frame.setVisible(true); 10 | } 11 | } 12 | -------------------------------------------------------------------------------- /src/Builder/A4/Builder.java: -------------------------------------------------------------------------------- 1 | public abstract class Builder { 2 | public abstract void makeTitle(String title); 3 | public abstract void makeString(String str); 4 | public abstract void makeItems(String[] items); 5 | public abstract void close(); 6 | } 7 | -------------------------------------------------------------------------------- /src/Builder/A4/Director.java: -------------------------------------------------------------------------------- 1 | public class Director { 2 | private Builder builder; 3 | public Director(Builder builder) { // 因为接收的参数是Builder类的子类 4 | this.builder = builder; // 所以可以将其保存在builder字段中 5 | } 6 | public void construct() { // 编写文档 7 | builder.makeTitle("Greeting"); // 标题 8 | builder.makeString("从早上至下午"); // 字符串 9 | builder.makeItems(new String[]{ // 条目 10 | "早上好。", 11 | "下午好。", 12 | }); 13 | builder.makeString("晚上"); // 其他字符串 14 | builder.makeItems(new String[]{ // 其他条目 15 | "晚上好。", 16 | "晚安。", 17 | "再见。", 18 | }); 19 | builder.close(); // 完成文档 20 | } 21 | } 22 | -------------------------------------------------------------------------------- /src/Builder/A4/Main.java: -------------------------------------------------------------------------------- 1 | public class Main { 2 | public static void main(String[] args) { 3 | if (args.length != 1) { 4 | usage(); 5 | System.exit(0); 6 | } 7 | if (args[0].equals("plain")) { 8 | TextBuilder textbuilder = new TextBuilder(); 9 | Director director = new Director(textbuilder); 10 | director.construct(); 11 | String result = textbuilder.getResult(); 12 | System.out.println(result); 13 | } else if (args[0].equals("html")) { 14 | HTMLBuilder htmlbuilder = new HTMLBuilder(); 15 | Director director = new Director(htmlbuilder); 16 | director.construct(); 17 | String filename = htmlbuilder.getResult(); 18 | System.out.println(filename + "文件编写完成。"); 19 | } else { 20 | usage(); 21 | System.exit(0); 22 | } 23 | } 24 | public static void usage() { 25 | System.out.println("Usage: java Main plain 编写纯文本文档"); 26 | System.out.println("Usage: java Main html 编写HTML文档"); 27 | } 28 | } 29 | -------------------------------------------------------------------------------- /src/Builder/Sample/Builder.java: -------------------------------------------------------------------------------- 1 | public abstract class Builder { 2 | public abstract void makeTitle(String title); 3 | public abstract void makeString(String str); 4 | public abstract void makeItems(String[] items); 5 | public abstract void close(); 6 | } 7 | -------------------------------------------------------------------------------- /src/Builder/Sample/Director.java: -------------------------------------------------------------------------------- 1 | public class Director { 2 | private Builder builder; 3 | public Director(Builder builder) { // 因为接收的参数是Builder类的子类 4 | this.builder = builder; // 所以可以将其保存在builder字段中 5 | } 6 | public void construct() { // 编写文档 7 | builder.makeTitle("Greeting"); // 标题 8 | builder.makeString("从早上至下午"); // 字符串 9 | builder.makeItems(new String[]{ // 条目 10 | "早上好。", 11 | "下午好。", 12 | }); 13 | builder.makeString("晚上"); // 其他字符串 14 | builder.makeItems(new String[]{ // 其他条目 15 | "晚上好。", 16 | "晚安。", 17 | "再见。", 18 | }); 19 | builder.close(); // 完成文档 20 | } 21 | } 22 | -------------------------------------------------------------------------------- /src/Builder/Sample/Main.java: -------------------------------------------------------------------------------- 1 | public class Main { 2 | public static void main(String[] args) { 3 | if (args.length != 1) { 4 | usage(); 5 | System.exit(0); 6 | } 7 | if (args[0].equals("plain")) { 8 | TextBuilder textbuilder = new TextBuilder(); 9 | Director director = new Director(textbuilder); 10 | director.construct(); 11 | String result = textbuilder.getResult(); 12 | System.out.println(result); 13 | } else if (args[0].equals("html")) { 14 | HTMLBuilder htmlbuilder = new HTMLBuilder(); 15 | Director director = new Director(htmlbuilder); 16 | director.construct(); 17 | String filename = htmlbuilder.getResult(); 18 | System.out.println(filename + "文件编写完成。"); 19 | } else { 20 | usage(); 21 | System.exit(0); 22 | } 23 | } 24 | public static void usage() { 25 | System.out.println("Usage: java Main plain 编写纯文本文档"); 26 | System.out.println("Usage: java Main html 编写HTML文档"); 27 | } 28 | } 29 | -------------------------------------------------------------------------------- /src/ChainOfResponsibility/A4/LimitSupport.java: -------------------------------------------------------------------------------- 1 | public class LimitSupport extends Support { 2 | private int limit; // 可以解决编号小于limit的问题 3 | public LimitSupport(String name, int limit) { // 构造函数 4 | super(name); 5 | this.limit = limit; 6 | } 7 | protected boolean resolve(Trouble trouble) { // 解决问题的方法 8 | if (trouble.getNumber() < limit) { 9 | return true; 10 | } else { 11 | return false; 12 | } 13 | } 14 | } 15 | -------------------------------------------------------------------------------- /src/ChainOfResponsibility/A4/Main.java: -------------------------------------------------------------------------------- 1 | public class Main { 2 | public static void main(String[] args) { 3 | Support alice = new NoSupport("Alice"); 4 | Support bob = new LimitSupport("Bob", 100); 5 | Support charlie = new SpecialSupport("Charlie", 429); 6 | Support diana = new LimitSupport("Diana", 200); 7 | Support elmo = new OddSupport("Elmo"); 8 | Support fred = new LimitSupport("Fred", 300); 9 | // 形成职责链 10 | alice.setNext(bob).setNext(charlie).setNext(diana).setNext(elmo).setNext(fred); 11 | // 制造各种问题 12 | for (int i = 0; i < 500; i += 33) { 13 | alice.support(new Trouble(i)); 14 | } 15 | } 16 | } 17 | -------------------------------------------------------------------------------- /src/ChainOfResponsibility/A4/NoSupport.java: -------------------------------------------------------------------------------- 1 | public class NoSupport extends Support { 2 | public NoSupport(String name) { 3 | super(name); 4 | } 5 | protected boolean resolve(Trouble trouble) { // 解决问题的方法 6 | return false; // 自己什么也不处理 7 | } 8 | } 9 | -------------------------------------------------------------------------------- /src/ChainOfResponsibility/A4/OddSupport.java: -------------------------------------------------------------------------------- 1 | public class OddSupport extends Support { 2 | public OddSupport(String name) { // 构造函数 3 | super(name); 4 | } 5 | protected boolean resolve(Trouble trouble) { // 解决问题的方法 6 | if (trouble.getNumber() % 2 == 1) { 7 | return true; 8 | } else { 9 | return false; 10 | } 11 | } 12 | } 13 | -------------------------------------------------------------------------------- /src/ChainOfResponsibility/A4/SpecialSupport.java: -------------------------------------------------------------------------------- 1 | public class SpecialSupport extends Support { 2 | private int number; // 只能解决指定编号的问题 3 | public SpecialSupport(String name, int number) { // 构造函数 4 | super(name); 5 | this.number = number; 6 | } 7 | protected boolean resolve(Trouble trouble) { // 解决问题的方法 8 | if (trouble.getNumber() == number) { 9 | return true; 10 | } else { 11 | return false; 12 | } 13 | } 14 | } 15 | -------------------------------------------------------------------------------- /src/ChainOfResponsibility/A4/Trouble.java: -------------------------------------------------------------------------------- 1 | public class Trouble { 2 | private int number; // 问题编号 3 | public Trouble(int number) { // 生成问题 4 | this.number = number; 5 | } 6 | public int getNumber() { // 获取问题编号 7 | return number; 8 | } 9 | public String toString() { // 代表问题的字符串 10 | return "[Trouble " + number + "]"; 11 | } 12 | } 13 | -------------------------------------------------------------------------------- /src/ChainOfResponsibility/Sample/LimitSupport.java: -------------------------------------------------------------------------------- 1 | public class LimitSupport extends Support { 2 | private int limit; // 可以解决编号小于limit的问题 3 | public LimitSupport(String name, int limit) { // 构造函数 4 | super(name); 5 | this.limit = limit; 6 | } 7 | protected boolean resolve(Trouble trouble) { // 解决问题的方法 8 | if (trouble.getNumber() < limit) { 9 | return true; 10 | } else { 11 | return false; 12 | } 13 | } 14 | } 15 | -------------------------------------------------------------------------------- /src/ChainOfResponsibility/Sample/Main.java: -------------------------------------------------------------------------------- 1 | public class Main { 2 | public static void main(String[] args) { 3 | Support alice = new NoSupport("Alice"); 4 | Support bob = new LimitSupport("Bob", 100); 5 | Support charlie = new SpecialSupport("Charlie", 429); 6 | Support diana = new LimitSupport("Diana", 200); 7 | Support elmo = new OddSupport("Elmo"); 8 | Support fred = new LimitSupport("Fred", 300); 9 | // 形成职责链 10 | alice.setNext(bob).setNext(charlie).setNext(diana).setNext(elmo).setNext(fred); 11 | // 制造各种问题 12 | for (int i = 0; i < 500; i += 33) { 13 | alice.support(new Trouble(i)); 14 | } 15 | } 16 | } 17 | -------------------------------------------------------------------------------- /src/ChainOfResponsibility/Sample/NoSupport.java: -------------------------------------------------------------------------------- 1 | public class NoSupport extends Support { 2 | public NoSupport(String name) { 3 | super(name); 4 | } 5 | protected boolean resolve(Trouble trouble) { // 解决问题的方法 6 | return false; // 自己什么也不处理 7 | } 8 | } 9 | -------------------------------------------------------------------------------- /src/ChainOfResponsibility/Sample/OddSupport.java: -------------------------------------------------------------------------------- 1 | public class OddSupport extends Support { 2 | public OddSupport(String name) { // 构造函数 3 | super(name); 4 | } 5 | protected boolean resolve(Trouble trouble) { // 解决问题的方法 6 | if (trouble.getNumber() % 2 == 1) { 7 | return true; 8 | } else { 9 | return false; 10 | } 11 | } 12 | } 13 | -------------------------------------------------------------------------------- /src/ChainOfResponsibility/Sample/SpecialSupport.java: -------------------------------------------------------------------------------- 1 | public class SpecialSupport extends Support { 2 | private int number; // 只能解决指定编号的问题 3 | public SpecialSupport(String name, int number) { // 构造函数 4 | super(name); 5 | this.number = number; 6 | } 7 | protected boolean resolve(Trouble trouble) { // 解决问题的方法 8 | if (trouble.getNumber() == number) { 9 | return true; 10 | } else { 11 | return false; 12 | } 13 | } 14 | } 15 | -------------------------------------------------------------------------------- /src/ChainOfResponsibility/Sample/Support.java: -------------------------------------------------------------------------------- 1 | public abstract class Support { 2 | private String name; // 解决问题的实例的名字 3 | private Support next; // 要推卸给的对象 4 | public Support(String name) { // 生成解决问题的实例 5 | this.name = name; 6 | } 7 | public Support setNext(Support next) { // 设置要推卸给的对象 8 | this.next = next; 9 | return next; 10 | } 11 | public void support(Trouble trouble) { // 解决问题的步骤 12 | if (resolve(trouble)) { 13 | done(trouble); 14 | } else if (next != null) { 15 | next.support(trouble); 16 | } else { 17 | fail(trouble); 18 | } 19 | } 20 | public String toString() { // 显示字符串 21 | return "[" + name + "]"; 22 | } 23 | protected abstract boolean resolve(Trouble trouble); // 解决问题的方法 24 | protected void done(Trouble trouble) { // 解决 25 | System.out.println(trouble + " is resolved by " + this + "."); 26 | } 27 | protected void fail(Trouble trouble) { // 未解决 28 | System.out.println(trouble + " cannot be resolved."); 29 | } 30 | } 31 | -------------------------------------------------------------------------------- /src/ChainOfResponsibility/Sample/Trouble.java: -------------------------------------------------------------------------------- 1 | public class Trouble { 2 | private int number; // 问题编号 3 | public Trouble(int number) { // 生成问题 4 | this.number = number; 5 | } 6 | public int getNumber() { // 获取问题编号 7 | return number; 8 | } 9 | public String toString() { // 代表问题的字符串 10 | return "[Trouble " + number + "]"; 11 | } 12 | } 13 | -------------------------------------------------------------------------------- /src/Command/A1/command/Command.java: -------------------------------------------------------------------------------- 1 | package command; 2 | 3 | public interface Command { 4 | public abstract void execute(); 5 | } 6 | -------------------------------------------------------------------------------- /src/Command/A1/command/MacroCommand.java: -------------------------------------------------------------------------------- 1 | package command; 2 | 3 | import java.util.Stack; 4 | import java.util.Iterator; 5 | 6 | public class MacroCommand implements Command { 7 | // 命令的集合 8 | private Stack commands = new Stack(); 9 | // 执行 10 | public void execute() { 11 | Iterator it = commands.iterator(); 12 | while (it.hasNext()) { 13 | ((Command)it.next()).execute(); 14 | } 15 | } 16 | // 添加命令 17 | public void append(Command cmd) { 18 | if (cmd != this) { 19 | commands.push(cmd); 20 | } 21 | } 22 | // 删除最后一条命令 23 | public void undo() { 24 | if (!commands.empty()) { 25 | commands.pop(); 26 | } 27 | } 28 | // 删除所有命令 29 | public void clear() { 30 | commands.clear(); 31 | } 32 | } 33 | -------------------------------------------------------------------------------- /src/Command/A1/drawer/ColorCommand.java: -------------------------------------------------------------------------------- 1 | package drawer; 2 | 3 | import command.Command; 4 | import java.awt.Color; 5 | 6 | public class ColorCommand implements Command { 7 | // 描画对象 8 | protected Drawable drawable; 9 | // 颜色 10 | private Color color; 11 | // 构造函数 12 | public ColorCommand(Drawable drawable, Color color) { 13 | this.drawable = drawable; 14 | this.color = color; 15 | } 16 | // 执行 17 | public void execute() { 18 | drawable.setColor(color); 19 | } 20 | } 21 | -------------------------------------------------------------------------------- /src/Command/A1/drawer/DrawCommand.java: -------------------------------------------------------------------------------- 1 | package drawer; 2 | 3 | import command.Command; 4 | import java.awt.Point; 5 | 6 | public class DrawCommand implements Command { 7 | // 绘制对象 8 | protected Drawable drawable; 9 | // 绘制位置 10 | private Point position; 11 | // 构造函数 12 | public DrawCommand(Drawable drawable, Point position) { 13 | this.drawable = drawable; 14 | this.position = position; 15 | } 16 | // 执行 17 | public void execute() { 18 | drawable.draw(position.x, position.y); 19 | } 20 | } 21 | -------------------------------------------------------------------------------- /src/Command/A1/drawer/Drawable.java: -------------------------------------------------------------------------------- 1 | package drawer; 2 | 3 | import java.awt.Color; 4 | 5 | public interface Drawable { 6 | public abstract void init(); 7 | public abstract void draw(int x, int y); 8 | public abstract void setColor(Color color); 9 | } 10 | -------------------------------------------------------------------------------- /src/Command/A2/command/Command.java: -------------------------------------------------------------------------------- 1 | package command; 2 | 3 | public interface Command { 4 | public abstract void execute(); 5 | } 6 | -------------------------------------------------------------------------------- /src/Command/A2/command/MacroCommand.java: -------------------------------------------------------------------------------- 1 | package command; 2 | 3 | import java.util.Stack; 4 | import java.util.Iterator; 5 | 6 | public class MacroCommand implements Command { 7 | // 命令的集合 8 | private Stack commands = new Stack(); 9 | // 执行 10 | public void execute() { 11 | Iterator it = commands.iterator(); 12 | while (it.hasNext()) { 13 | ((Command)it.next()).execute(); 14 | } 15 | } 16 | // 添加命令 17 | public void append(Command cmd) { 18 | if (cmd != this) { 19 | commands.push(cmd); 20 | } 21 | } 22 | // 删除最后一条命令 23 | public void undo() { 24 | if (!commands.empty()) { 25 | commands.pop(); 26 | } 27 | } 28 | // 删除所有命令 29 | public void clear() { 30 | commands.clear(); 31 | } 32 | } 33 | -------------------------------------------------------------------------------- /src/Command/A2/drawer/DrawCanvas.java: -------------------------------------------------------------------------------- 1 | package drawer; 2 | 3 | import command.*; 4 | 5 | import java.util.*; 6 | import java.awt.*; 7 | import java.awt.event.*; 8 | import javax.swing.*; 9 | 10 | public class DrawCanvas extends Canvas implements Drawable { 11 | // 颜色 12 | private Color color = Color.red; 13 | // 要绘制的圆点的半径 14 | private int radius = 6; 15 | // 命令的历史记录 16 | private MacroCommand history; 17 | // 构造函数 18 | public DrawCanvas(int width, int height, MacroCommand history) { 19 | setSize(width, height); 20 | setBackground(Color.white); 21 | this.history = history; 22 | } 23 | // 重新全部绘制 24 | public void paint(Graphics g) { 25 | history.execute(); 26 | } 27 | // 绘制 28 | public void draw(int x, int y) { 29 | Graphics g = getGraphics(); 30 | g.setColor(color); 31 | g.fillOval(x - radius, y - radius, radius * 2, radius * 2); 32 | } 33 | } 34 | -------------------------------------------------------------------------------- /src/Command/A2/drawer/DrawCommand.java: -------------------------------------------------------------------------------- 1 | package drawer; 2 | 3 | import command.Command; 4 | import java.awt.Point; 5 | 6 | public class DrawCommand implements Command { 7 | // 绘制对象 8 | protected Drawable drawable; 9 | // 绘制位置 10 | private Point position; 11 | // 构造函数 12 | public DrawCommand(Drawable drawable, Point position) { 13 | this.drawable = drawable; 14 | this.position = position; 15 | } 16 | // 执行 17 | public void execute() { 18 | drawable.draw(position.x, position.y); 19 | } 20 | } 21 | -------------------------------------------------------------------------------- /src/Command/A2/drawer/Drawable.java: -------------------------------------------------------------------------------- 1 | package drawer; 2 | 3 | public interface Drawable { 4 | public abstract void draw(int x, int y); 5 | } 6 | -------------------------------------------------------------------------------- /src/Command/A3/command/Command.java: -------------------------------------------------------------------------------- 1 | package command; 2 | 3 | public interface Command { 4 | public abstract void execute(); 5 | } 6 | -------------------------------------------------------------------------------- /src/Command/A3/command/MacroCommand.java: -------------------------------------------------------------------------------- 1 | package command; 2 | 3 | import java.util.Stack; 4 | import java.util.Iterator; 5 | 6 | public class MacroCommand implements Command { 7 | // 命令的集合 8 | private Stack commands = new Stack(); 9 | // 执行 10 | public void execute() { 11 | Iterator it = commands.iterator(); 12 | while (it.hasNext()) { 13 | ((Command)it.next()).execute(); 14 | } 15 | } 16 | // 添加命令 17 | public void append(Command cmd) { 18 | if (cmd != this) { 19 | commands.push(cmd); 20 | } 21 | } 22 | // 删除最后一条命令 23 | public void undo() { 24 | if (!commands.empty()) { 25 | commands.pop(); 26 | } 27 | } 28 | // 删除所有命令 29 | public void clear() { 30 | commands.clear(); 31 | } 32 | } 33 | -------------------------------------------------------------------------------- /src/Command/A3/drawer/DrawCanvas.java: -------------------------------------------------------------------------------- 1 | package drawer; 2 | 3 | import command.*; 4 | 5 | import java.util.*; 6 | import java.awt.*; 7 | import java.awt.event.*; 8 | import javax.swing.*; 9 | 10 | public class DrawCanvas extends Canvas implements Drawable { 11 | // 颜色 12 | private Color color = Color.red; 13 | // 要绘制的圆点的半径 14 | private int radius = 6; 15 | // 命令的历史记录 16 | private MacroCommand history; 17 | // 构造函数 18 | public DrawCanvas(int width, int height, MacroCommand history) { 19 | setSize(width, height); 20 | setBackground(Color.white); 21 | this.history = history; 22 | } 23 | // 重新全部绘制 24 | public void paint(Graphics g) { 25 | history.execute(); 26 | } 27 | // 绘制 28 | public void draw(int x, int y) { 29 | Graphics g = getGraphics(); 30 | g.setColor(color); 31 | g.fillOval(x - radius, y - radius, radius * 2, radius * 2); 32 | } 33 | } 34 | -------------------------------------------------------------------------------- /src/Command/A3/drawer/DrawCommand.java: -------------------------------------------------------------------------------- 1 | package drawer; 2 | 3 | import command.Command; 4 | import java.awt.Point; 5 | 6 | public class DrawCommand implements Command { 7 | // 绘制对象 8 | protected Drawable drawable; 9 | // 绘制位置 10 | private Point position; 11 | // 构造函数 12 | public DrawCommand(Drawable drawable, Point position) { 13 | this.drawable = drawable; 14 | this.position = position; 15 | } 16 | // 执行 17 | public void execute() { 18 | drawable.draw(position.x, position.y); 19 | } 20 | } 21 | -------------------------------------------------------------------------------- /src/Command/A3/drawer/Drawable.java: -------------------------------------------------------------------------------- 1 | package drawer; 2 | 3 | public interface Drawable { 4 | public abstract void draw(int x, int y); 5 | } 6 | -------------------------------------------------------------------------------- /src/Command/Sample/command/Command.java: -------------------------------------------------------------------------------- 1 | package command; 2 | 3 | public interface Command { 4 | public abstract void execute(); 5 | } 6 | -------------------------------------------------------------------------------- /src/Command/Sample/command/MacroCommand.java: -------------------------------------------------------------------------------- 1 | package command; 2 | 3 | import java.util.Stack; 4 | import java.util.Iterator; 5 | 6 | public class MacroCommand implements Command { 7 | // 命令的集合 8 | private Stack commands = new Stack(); 9 | // 执行 10 | public void execute() { 11 | Iterator it = commands.iterator(); 12 | while (it.hasNext()) { 13 | ((Command)it.next()).execute(); 14 | } 15 | } 16 | // 添加命令 17 | public void append(Command cmd) { 18 | if (cmd != this) { 19 | commands.push(cmd); 20 | } 21 | } 22 | // 删除最后一条命令 23 | public void undo() { 24 | if (!commands.empty()) { 25 | commands.pop(); 26 | } 27 | } 28 | // 删除所有命令 29 | public void clear() { 30 | commands.clear(); 31 | } 32 | } 33 | -------------------------------------------------------------------------------- /src/Command/Sample/drawer/DrawCanvas.java: -------------------------------------------------------------------------------- 1 | package drawer; 2 | 3 | import command.*; 4 | 5 | import java.util.*; 6 | import java.awt.*; 7 | import java.awt.event.*; 8 | import javax.swing.*; 9 | 10 | public class DrawCanvas extends Canvas implements Drawable { 11 | // 颜色 12 | private Color color = Color.red; 13 | // 要绘制的圆点的半径 14 | private int radius = 6; 15 | // 命令的历史记录 16 | private MacroCommand history; 17 | // 构造函数 18 | public DrawCanvas(int width, int height, MacroCommand history) { 19 | setSize(width, height); 20 | setBackground(Color.white); 21 | this.history = history; 22 | } 23 | // 重新全部绘制 24 | public void paint(Graphics g) { 25 | history.execute(); 26 | } 27 | // 绘制 28 | public void draw(int x, int y) { 29 | Graphics g = getGraphics(); 30 | g.setColor(color); 31 | g.fillOval(x - radius, y - radius, radius * 2, radius * 2); 32 | } 33 | } 34 | -------------------------------------------------------------------------------- /src/Command/Sample/drawer/DrawCommand.java: -------------------------------------------------------------------------------- 1 | package drawer; 2 | 3 | import command.Command; 4 | import java.awt.Point; 5 | 6 | public class DrawCommand implements Command { 7 | // 绘制对象 8 | protected Drawable drawable; 9 | // 绘制位置 10 | private Point position; 11 | // 构造函数 12 | public DrawCommand(Drawable drawable, Point position) { 13 | this.drawable = drawable; 14 | this.position = position; 15 | } 16 | // 执行 17 | public void execute() { 18 | drawable.draw(position.x, position.y); 19 | } 20 | } 21 | -------------------------------------------------------------------------------- /src/Command/Sample/drawer/Drawable.java: -------------------------------------------------------------------------------- 1 | package drawer; 2 | 3 | public interface Drawable { 4 | public abstract void draw(int x, int y); 5 | } 6 | -------------------------------------------------------------------------------- /src/Composite/A2/Directory.java: -------------------------------------------------------------------------------- 1 | import java.util.Iterator; 2 | import java.util.ArrayList; 3 | 4 | public class Directory extends Entry { 5 | private String name; 6 | private ArrayList directory = new ArrayList(); 7 | public Directory(String name) { 8 | this.name = name; 9 | } 10 | public String getName() { 11 | return name; 12 | } 13 | public int getSize() { 14 | int size = 0; 15 | Iterator it = directory.iterator(); 16 | while (it.hasNext()) { 17 | Entry entry = (Entry)it.next(); 18 | size += entry.getSize(); 19 | } 20 | return size; 21 | } 22 | public Entry add(Entry entry) { 23 | directory.add(entry); 24 | entry.parent = this; 25 | return this; 26 | } 27 | protected void printList(String prefix) { 28 | System.out.println(prefix + "/" + this); 29 | Iterator it = directory.iterator(); 30 | while (it.hasNext()) { 31 | Entry entry = (Entry)it.next(); 32 | entry.printList(prefix + "/" + name); 33 | } 34 | } 35 | } 36 | -------------------------------------------------------------------------------- /src/Composite/A2/Entry.java: -------------------------------------------------------------------------------- 1 | public abstract class Entry { 2 | protected Entry parent; 3 | public abstract String getName(); 4 | public abstract int getSize(); 5 | public Entry add(Entry entry) throws FileTreatmentException { 6 | throw new FileTreatmentException(); 7 | } 8 | public void printList() { 9 | printList(""); 10 | } 11 | protected abstract void printList(String prefix); 12 | public String toString() { 13 | return getName() + " (" + getSize() + ")"; 14 | } 15 | public String getFullName() { 16 | StringBuffer fullname = new StringBuffer(); 17 | Entry entry = this; 18 | do { 19 | fullname.insert(0, "/" + entry.getName()); 20 | entry = entry.parent; 21 | } while (entry != null); 22 | return fullname.toString(); 23 | } 24 | } 25 | -------------------------------------------------------------------------------- /src/Composite/A2/File.java: -------------------------------------------------------------------------------- 1 | public class File extends Entry { 2 | private String name; 3 | private int size; 4 | public File(String name, int size) { 5 | this.name = name; 6 | this.size = size; 7 | } 8 | public String getName() { 9 | return name; 10 | } 11 | public int getSize() { 12 | return size; 13 | } 14 | protected void printList(String prefix) { 15 | System.out.println(prefix + "/" + this); 16 | } 17 | } 18 | -------------------------------------------------------------------------------- /src/Composite/A2/FileTreatmentException.java: -------------------------------------------------------------------------------- 1 | public class FileTreatmentException extends RuntimeException { 2 | public FileTreatmentException() { 3 | } 4 | public FileTreatmentException(String msg) { 5 | super(msg); 6 | } 7 | } 8 | -------------------------------------------------------------------------------- /src/Composite/A2/Main.java: -------------------------------------------------------------------------------- 1 | public class Main { 2 | public static void main(String[] args) { 3 | try { 4 | Directory rootdir = new Directory("root"); 5 | 6 | Directory usrdir = new Directory("usr"); 7 | rootdir.add(usrdir); 8 | 9 | Directory yuki = new Directory("yuki"); 10 | usrdir.add(yuki); 11 | 12 | File file = new File("Composite.java", 100); 13 | yuki.add(file); 14 | rootdir.printList(); 15 | 16 | System.out.println(""); 17 | System.out.println("file = " + file.getFullName()); 18 | System.out.println("yuki = " + yuki.getFullName()); 19 | } catch (FileTreatmentException e) { 20 | e.printStackTrace(); 21 | } 22 | } 23 | } 24 | -------------------------------------------------------------------------------- /src/Composite/Sample/Entry.java: -------------------------------------------------------------------------------- 1 | public abstract class Entry { 2 | public abstract String getName(); // 获取名字 3 | public abstract int getSize(); // 获取大小 4 | public Entry add(Entry entry) throws FileTreatmentException { // 加入目录条目 5 | throw new FileTreatmentException(); 6 | } 7 | public void printList() { // 为一览加上前缀并显示目录条目一览 8 | printList(""); 9 | } 10 | protected abstract void printList(String prefix); // 为一览加上前缀 11 | public String toString() { // 显示代表类的文字 12 | return getName() + " (" + getSize() + ")"; 13 | } 14 | } 15 | -------------------------------------------------------------------------------- /src/Composite/Sample/File.java: -------------------------------------------------------------------------------- 1 | public class File extends Entry { 2 | private String name; 3 | private int size; 4 | public File(String name, int size) { 5 | this.name = name; 6 | this.size = size; 7 | } 8 | public String getName() { 9 | return name; 10 | } 11 | public int getSize() { 12 | return size; 13 | } 14 | protected void printList(String prefix) { 15 | System.out.println(prefix + "/" + this); 16 | } 17 | } 18 | -------------------------------------------------------------------------------- /src/Composite/Sample/FileTreatmentException.java: -------------------------------------------------------------------------------- 1 | public class FileTreatmentException extends RuntimeException { 2 | public FileTreatmentException() { 3 | } 4 | public FileTreatmentException(String msg) { 5 | super(msg); 6 | } 7 | } 8 | -------------------------------------------------------------------------------- /src/Decorator/A1/Border.java: -------------------------------------------------------------------------------- 1 | public abstract class Border extends Display { 2 | protected Display display; // 表示被装饰物 3 | protected Border(Display display) { // 在生成实例时通过参数指定 被装饰物 4 | this.display = display; 5 | } 6 | } 7 | -------------------------------------------------------------------------------- /src/Decorator/A1/Display.java: -------------------------------------------------------------------------------- 1 | public abstract class Display { 2 | public abstract int getColumns(); // 获取横向字符数 3 | public abstract int getRows(); // 获取纵向行数 4 | public abstract String getRowText(int row); // 获取第row行的字符串 5 | public void show() { // 全部显示 6 | for (int i = 0; i < getRows(); i++) { 7 | System.out.println(getRowText(i)); 8 | } 9 | } 10 | } 11 | -------------------------------------------------------------------------------- /src/Decorator/A1/Main.java: -------------------------------------------------------------------------------- 1 | public class Main { 2 | public static void main(String[] args) { 3 | Display b1 = new StringDisplay("Hello, world."); 4 | Display b2 = new UpDownBorder(b1, '-'); 5 | Display b3 = new SideBorder(b2, '*'); 6 | b1.show(); 7 | b2.show(); 8 | b3.show(); 9 | Display b4 = 10 | new FullBorder( 11 | new UpDownBorder( 12 | new SideBorder( 13 | new UpDownBorder( 14 | new SideBorder( 15 | new StringDisplay("你好,世界。"), 16 | '*' 17 | ), 18 | '=' 19 | ), 20 | '|' 21 | ), 22 | '/' 23 | ) 24 | ); 25 | b4.show(); 26 | } 27 | } 28 | -------------------------------------------------------------------------------- /src/Decorator/A1/SideBorder.java: -------------------------------------------------------------------------------- 1 | public class SideBorder extends Border { 2 | private char borderChar; // 表示装饰边框的文字 3 | public SideBorder(Display display, char ch) { // 通过构造函数指定Display和边框文字 4 | super(display); 5 | this.borderChar = ch; 6 | } 7 | public int getColumns() { // 字符数为字符串字符数加上两侧边框字符数 8 | return 1 + display.getColumns() + 1; 9 | } 10 | public int getRows() { // 行数即被装饰物的行数 11 | return display.getRows(); 12 | } 13 | public String getRowText(int row) { // 指定的那一行的字符串为被装饰物的字符串加上两侧的边框的字符 14 | return borderChar + display.getRowText(row) + borderChar; 15 | } 16 | } 17 | -------------------------------------------------------------------------------- /src/Decorator/A1/StringDisplay.java: -------------------------------------------------------------------------------- 1 | public class StringDisplay extends Display { 2 | private String string; // 要显示的字符串 3 | public StringDisplay(String string) { // 通过参数传入要显示的字符串 4 | this.string = string; 5 | } 6 | public int getColumns() { // 字符数 7 | return string.getBytes().length; 8 | } 9 | public int getRows() { // 行数是1 10 | return 1; 11 | } 12 | public String getRowText(int row) { // 仅当row为0时返回值 13 | if (row == 0) { 14 | return string; 15 | } else { 16 | return null; 17 | } 18 | } 19 | } 20 | -------------------------------------------------------------------------------- /src/Decorator/A1/UpDownBorder.java: -------------------------------------------------------------------------------- 1 | public class UpDownBorder extends Border { 2 | private char borderChar; // 表示装饰边框的字符 3 | public UpDownBorder(Display display, char ch) { // 通过构造函数指定Display和装饰边框字符 4 | super(display); 5 | this.borderChar = ch; 6 | } 7 | public int getColumns() { // 列数与要显示的内容的字符数相同 8 | return display.getColumns(); 9 | } 10 | public int getRows() { // 行数是内容的行数加上上下边框 11 | return 1 + display.getRows() + 1; 12 | } 13 | public String getRowText(int row) { // 获取指定行的内容 14 | if (row == 0 || row == getRows() - 1) { 15 | return makeLine(borderChar, getColumns()); 16 | } else { 17 | return display.getRowText(row - 1); 18 | } 19 | } 20 | private String makeLine(char ch, int count) { // 生成一个由count个字符ch连续组成的字符串 21 | StringBuffer buf = new StringBuffer(); 22 | for (int i = 0; i < count; i++) { 23 | buf.append(ch); 24 | } 25 | return buf.toString(); 26 | } 27 | } 28 | -------------------------------------------------------------------------------- /src/Decorator/A2/Border.java: -------------------------------------------------------------------------------- 1 | public abstract class Border extends Display { 2 | protected Display display; // 表示被装饰物 3 | protected Border(Display display) { // 在生成实例时通过参数指定 被装饰物 4 | this.display = display; 5 | } 6 | } 7 | -------------------------------------------------------------------------------- /src/Decorator/A2/Display.java: -------------------------------------------------------------------------------- 1 | public abstract class Display { 2 | public abstract int getColumns(); // 获取横向字符数 3 | public abstract int getRows(); // 获取纵向行数 4 | public abstract String getRowText(int row); // 获取第row行的字符串 5 | public void show() { // 全部显示 6 | for (int i = 0; i < getRows(); i++) { 7 | System.out.println(getRowText(i)); 8 | } 9 | } 10 | } 11 | -------------------------------------------------------------------------------- /src/Decorator/A2/Main.java: -------------------------------------------------------------------------------- 1 | public class Main { 2 | public static void main(String[] args) { 3 | MultiStringDisplay md = new MultiStringDisplay(); 4 | md.add("早上好。"); 5 | md.add("下午好。"); 6 | md.add("晚安,明天见。"); 7 | md.show(); 8 | 9 | Display d1 = new SideBorder(md, '#'); 10 | d1.show(); 11 | 12 | Display d2 = new FullBorder(md); 13 | d2.show(); 14 | } 15 | } 16 | -------------------------------------------------------------------------------- /src/Decorator/A2/SideBorder.java: -------------------------------------------------------------------------------- 1 | public class SideBorder extends Border { 2 | private char borderChar; // 表示装饰边框的文字 3 | public SideBorder(Display display, char ch) { // 通过构造函数指定Display和边框文字 4 | super(display); 5 | this.borderChar = ch; 6 | } 7 | public int getColumns() { // 字符数为字符串字符数加上两侧边框字符数 8 | return 1 + display.getColumns() + 1; 9 | } 10 | public int getRows() { // 行数即被装饰物的行数 11 | return display.getRows(); 12 | } 13 | public String getRowText(int row) { // 指定的那一行的字符串为被装饰物的字符串加上两侧的边框的字符 14 | return borderChar + display.getRowText(row) + borderChar; 15 | } 16 | } 17 | -------------------------------------------------------------------------------- /src/Decorator/A2/StringDisplay.java: -------------------------------------------------------------------------------- 1 | public class StringDisplay extends Display { 2 | private String string; // 要显示的字符串 3 | public StringDisplay(String string) { // 通过参数传入要显示的字符串 4 | this.string = string; 5 | } 6 | public int getColumns() { // 字符数 7 | return string.getBytes().length; 8 | } 9 | public int getRows() { // 行数是1 10 | return 1; 11 | } 12 | public String getRowText(int row) { // 仅当row为0时返回值 13 | if (row == 0) { 14 | return string; 15 | } else { 16 | return null; 17 | } 18 | } 19 | } 20 | -------------------------------------------------------------------------------- /src/Decorator/Q1/Main.java: -------------------------------------------------------------------------------- 1 | public class Main { 2 | public static void main(String[] args) { 3 | Display b1 = new StringDisplay("Hello, world."); 4 | Display b2 = new UpDownBorder(b1, '-'); 5 | Display b3 = new SideBorder(b2, '*'); 6 | b1.show(); 7 | b2.show(); 8 | b3.show(); 9 | Display b4 = 10 | new FullBorder( 11 | new UpDownBorder( 12 | new SideBorder( 13 | new UpDownBorder( 14 | new SideBorder( 15 | new StringDisplay("你好,世界。"), 16 | '*' 17 | ), 18 | '=' 19 | ), 20 | '|' 21 | ), 22 | '/' 23 | ) 24 | ); 25 | b4.show(); 26 | } 27 | } 28 | -------------------------------------------------------------------------------- /src/Decorator/Q2/Main.java: -------------------------------------------------------------------------------- 1 | public class Main { 2 | public static void main(String[] args) { 3 | MultiStringDisplay md = new MultiStringDisplay(); 4 | md.add("早上好。"); 5 | md.add("下午好。"); 6 | md.add("晚安,明天见。"); 7 | md.show(); 8 | 9 | Display d1 = new SideBorder(md, '#'); 10 | d1.show(); 11 | 12 | Display d2 = new FullBorder(md); 13 | d2.show(); 14 | } 15 | } 16 | -------------------------------------------------------------------------------- /src/Decorator/Sample/Border.java: -------------------------------------------------------------------------------- 1 | public abstract class Border extends Display { 2 | protected Display display; // 表示被装饰物 3 | protected Border(Display display) { // 在生成实例时通过参数指定被装饰物 4 | this.display = display; 5 | } 6 | } 7 | -------------------------------------------------------------------------------- /src/Decorator/Sample/Display.java: -------------------------------------------------------------------------------- 1 | public abstract class Display { 2 | public abstract int getColumns(); // 获取横向字符数 3 | public abstract int getRows(); // 获取纵向行数 4 | public abstract String getRowText(int row); // 获取第row行的字符串 5 | public void show() { // 全部显示 6 | for (int i = 0; i < getRows(); i++) { 7 | System.out.println(getRowText(i)); 8 | } 9 | } 10 | } 11 | -------------------------------------------------------------------------------- /src/Decorator/Sample/Main.java: -------------------------------------------------------------------------------- 1 | public class Main { 2 | public static void main(String[] args) { 3 | Display b1 = new StringDisplay("Hello, world."); 4 | Display b2 = new SideBorder(b1, '#'); 5 | Display b3 = new FullBorder(b2); 6 | b1.show(); 7 | b2.show(); 8 | b3.show(); 9 | Display b4 = 10 | new SideBorder( 11 | new FullBorder( 12 | new FullBorder( 13 | new SideBorder( 14 | new FullBorder( 15 | new StringDisplay("你好,世界。") 16 | ), 17 | '*' 18 | ) 19 | ) 20 | ), 21 | '/' 22 | ); 23 | b4.show(); 24 | } 25 | } 26 | -------------------------------------------------------------------------------- /src/Decorator/Sample/SideBorder.java: -------------------------------------------------------------------------------- 1 | public class SideBorder extends Border { 2 | private char borderChar; // 表示装饰边框的字符 3 | public SideBorder(Display display, char ch) { // 通过构造函数指定Display和装饰边框字符 4 | super(display); 5 | this.borderChar = ch; 6 | } 7 | public int getColumns() { // 字符数为字符串字符数加上两侧边框字符数 8 | return 1 + display.getColumns() + 1; 9 | } 10 | public int getRows() { // 行数即被装饰物的行数 11 | return display.getRows(); 12 | } 13 | public String getRowText(int row) { // 指定的那一行的字符串为被装饰物的字符串加上两侧的边框的字符 14 | return borderChar + display.getRowText(row) + borderChar; 15 | } 16 | } 17 | -------------------------------------------------------------------------------- /src/Decorator/Sample/StringDisplay.java: -------------------------------------------------------------------------------- 1 | public class StringDisplay extends Display { 2 | private String string; // 要显示的字符串 3 | public StringDisplay(String string) { // 通过参数传入要显示的字符串 4 | this.string = string; 5 | } 6 | public int getColumns() { // 字符数 7 | return string.getBytes().length; 8 | } 9 | public int getRows() { // 行数是1 10 | return 1; 11 | } 12 | public String getRowText(int row) { // 仅当row为0时返回值 13 | if (row == 0) { 14 | return string; 15 | } else { 16 | return null; 17 | } 18 | } 19 | } 20 | -------------------------------------------------------------------------------- /src/Facade/A2/Main.java: -------------------------------------------------------------------------------- 1 | import pagemaker.PageMaker; 2 | 3 | public class Main { 4 | public static void main(String[] args) { 5 | PageMaker.makeLinkPage("linkpage.html"); 6 | } 7 | } 8 | -------------------------------------------------------------------------------- /src/Facade/A2/maildata.txt: -------------------------------------------------------------------------------- 1 | hyuki@hyuki.com=Hiroshi Yuki 2 | hanako@hyuki.com=Hanako Sato 3 | tomura@hyuki.com=Tomura 4 | mamoru@hyuki.com=Mamoru Takahashi 5 | -------------------------------------------------------------------------------- /src/Facade/A2/pagemaker/Database.java: -------------------------------------------------------------------------------- 1 | package pagemaker; 2 | 3 | import java.io.FileInputStream; 4 | import java.io.IOException; 5 | import java.util.Properties; 6 | 7 | public class Database { 8 | private Database() { // 防止外部new出Database的实例,所以声明为private方法 9 | } 10 | public static Properties getProperties(String dbname) { // 根据数据库名获取Properties 11 | String filename = dbname + ".txt"; 12 | Properties prop = new Properties(); 13 | try { 14 | prop.load(new FileInputStream(filename)); 15 | } catch (IOException e) { 16 | System.out.println("Warning: " + filename + " is not found."); 17 | } 18 | return prop; 19 | } 20 | } 21 | -------------------------------------------------------------------------------- /src/Facade/Q2/Main.java: -------------------------------------------------------------------------------- 1 | import pagemaker.PageMaker; 2 | 3 | public class Main { 4 | public static void main(String[] args) { 5 | PageMaker.makeLinkPage("linkpage.html"); 6 | } 7 | } 8 | -------------------------------------------------------------------------------- /src/Facade/Sample/Main.java: -------------------------------------------------------------------------------- 1 | import pagemaker.PageMaker; 2 | 3 | public class Main { 4 | public static void main(String[] args) { 5 | PageMaker.makeWelcomePage("hyuki@hyuki.com", "welcome.html"); 6 | } 7 | } 8 | -------------------------------------------------------------------------------- /src/Facade/Sample/maildata.txt: -------------------------------------------------------------------------------- 1 | hyuki@hyuki.com=Hiroshi Yuki 2 | hanako@hyuki.com=Hanako Sato 3 | tomura@hyuki.com=Tomura 4 | mamoru@hyuki.com=Mamoru Takahashi 5 | -------------------------------------------------------------------------------- /src/Facade/Sample/pagemaker/Database.java: -------------------------------------------------------------------------------- 1 | package pagemaker; 2 | 3 | import java.io.FileInputStream; 4 | import java.io.IOException; 5 | import java.util.Properties; 6 | 7 | public class Database { 8 | private Database() { // 防止外部new出Database的实例,所以声明为private方法 9 | } 10 | public static Properties getProperties(String dbname) { // 根据数据库名获取Properties 11 | String filename = dbname + ".txt"; 12 | Properties prop = new Properties(); 13 | try { 14 | prop.load(new FileInputStream(filename)); 15 | } catch (IOException e) { 16 | System.out.println("Warning: " + filename + " is not found."); 17 | } 18 | return prop; 19 | } 20 | } 21 | -------------------------------------------------------------------------------- /src/Facade/Sample/pagemaker/PageMaker.java: -------------------------------------------------------------------------------- 1 | package pagemaker; 2 | 3 | import java.io.FileWriter; 4 | import java.io.IOException; 5 | import java.util.Properties; 6 | 7 | public class PageMaker { 8 | private PageMaker() { // 防止外部new出PageMaker的实例,所以声明为private方法 9 | } 10 | public static void makeWelcomePage(String mailaddr, String filename) { 11 | try { 12 | Properties mailprop = Database.getProperties("maildata"); 13 | String username = mailprop.getProperty(mailaddr); 14 | HtmlWriter writer = new HtmlWriter(new FileWriter(filename)); 15 | writer.title("Welcome to " + username + "'s page!"); 16 | writer.paragraph("欢迎来到" + username + "的主页。"); 17 | writer.paragraph("等着你的邮件哦!"); 18 | writer.mailto(mailaddr, username); 19 | writer.close(); 20 | System.out.println(filename + " is created for " + mailaddr + " (" + username + ")"); 21 | } catch (IOException e) { 22 | e.printStackTrace(); 23 | } 24 | } 25 | } 26 | -------------------------------------------------------------------------------- /src/FactoryMethod/A2/Main.java: -------------------------------------------------------------------------------- 1 | import framework.*; 2 | import idcard.*; 3 | 4 | public class Main { 5 | public static void main(String[] args) { 6 | Factory factory = new IDCardFactory(); 7 | Product card1 = factory.create("小明"); 8 | Product card2 = factory.create("小红"); 9 | Product card3 = factory.create("小刚"); 10 | card1.use(); 11 | card2.use(); 12 | card3.use(); 13 | } 14 | } 15 | -------------------------------------------------------------------------------- /src/FactoryMethod/A2/framework/Factory.java: -------------------------------------------------------------------------------- 1 | package framework; 2 | 3 | public abstract class Factory { 4 | public final Product create(String owner) { 5 | Product p = createProduct(owner); 6 | registerProduct(p); 7 | return p; 8 | } 9 | protected abstract Product createProduct(String owner); 10 | protected abstract void registerProduct(Product product); 11 | } 12 | -------------------------------------------------------------------------------- /src/FactoryMethod/A2/framework/Product.java: -------------------------------------------------------------------------------- 1 | package framework; 2 | 3 | public abstract class Product { 4 | public abstract void use(); 5 | } 6 | -------------------------------------------------------------------------------- /src/FactoryMethod/A2/idcard/IDCard.java: -------------------------------------------------------------------------------- 1 | package idcard; 2 | import framework.*; 3 | 4 | public class IDCard extends Product { 5 | private String owner; 6 | private int serial; 7 | IDCard(String owner, int serial) { 8 | System.out.println("制作" + owner + "(" + serial + ")" + "的ID卡。"); 9 | this.owner = owner; 10 | this.serial = serial; 11 | } 12 | public void use() { 13 | System.out.println("使用" + owner + "(" + serial + ")" + "的ID卡。"); 14 | } 15 | public String getOwner() { 16 | return owner; 17 | } 18 | public int getSerial() { 19 | return serial; 20 | } 21 | } 22 | -------------------------------------------------------------------------------- /src/FactoryMethod/A2/idcard/IDCardFactory.java: -------------------------------------------------------------------------------- 1 | package idcard; 2 | import framework.*; 3 | import java.util.*; 4 | 5 | public class IDCardFactory extends Factory { 6 | private HashMap database = new HashMap(); 7 | private int serial = 100; 8 | protected synchronized Product createProduct(String owner) { 9 | return new IDCard(owner, serial++); 10 | } 11 | protected void registerProduct(Product product) { 12 | IDCard card = (IDCard)product; 13 | database.put(new Integer(card.getSerial()), card.getOwner()); 14 | } 15 | public HashMap getDatabase() { 16 | return database; 17 | } 18 | } 19 | -------------------------------------------------------------------------------- /src/FactoryMethod/Sample/Main.java: -------------------------------------------------------------------------------- 1 | import framework.*; 2 | import idcard.*; 3 | 4 | public class Main { 5 | public static void main(String[] args) { 6 | Factory factory = new IDCardFactory(); 7 | Product card1 = factory.create("小明"); 8 | Product card2 = factory.create("小红"); 9 | Product card3 = factory.create("小刚"); 10 | card1.use(); 11 | card2.use(); 12 | card3.use(); 13 | } 14 | } 15 | -------------------------------------------------------------------------------- /src/FactoryMethod/Sample/framework/Factory.java: -------------------------------------------------------------------------------- 1 | package framework; 2 | 3 | public abstract class Factory { 4 | public final Product create(String owner) { 5 | Product p = createProduct(owner); 6 | registerProduct(p); 7 | return p; 8 | } 9 | protected abstract Product createProduct(String owner); 10 | protected abstract void registerProduct(Product product); 11 | } 12 | -------------------------------------------------------------------------------- /src/FactoryMethod/Sample/framework/Product.java: -------------------------------------------------------------------------------- 1 | package framework; 2 | 3 | public abstract class Product { 4 | public abstract void use(); 5 | } 6 | -------------------------------------------------------------------------------- /src/FactoryMethod/Sample/idcard/IDCard.java: -------------------------------------------------------------------------------- 1 | package idcard; 2 | import framework.*; 3 | 4 | public class IDCard extends Product { 5 | private String owner; 6 | IDCard(String owner) { 7 | System.out.println("制作" + owner + "的ID卡。"); 8 | this.owner = owner; 9 | } 10 | public void use() { 11 | System.out.println("使用" + owner + "的ID卡。"); 12 | } 13 | public String getOwner() { 14 | return owner; 15 | } 16 | } 17 | -------------------------------------------------------------------------------- /src/FactoryMethod/Sample/idcard/IDCardFactory.java: -------------------------------------------------------------------------------- 1 | package idcard; 2 | import framework.*; 3 | import java.util.*; 4 | 5 | public class IDCardFactory extends Factory { 6 | private List owners = new ArrayList(); 7 | protected Product createProduct(String owner) { 8 | return new IDCard(owner); 9 | } 10 | protected void registerProduct(Product product) { 11 | owners.add(((IDCard)product).getOwner()); 12 | } 13 | public List getOwners() { 14 | return owners; 15 | } 16 | } 17 | -------------------------------------------------------------------------------- /src/Flyweight/A1/BigChar.java: -------------------------------------------------------------------------------- 1 | import java.io.BufferedReader; 2 | import java.io.FileReader; 3 | import java.io.IOException; 4 | 5 | public class BigChar { 6 | // 字符名字 7 | private char charname; 8 | // 大型字符对应的字符串(由'#' '.' '\n'组成) 9 | private String fontdata; 10 | // 构造函数 11 | public BigChar(char charname) { 12 | this.charname = charname; 13 | try { 14 | BufferedReader reader = new BufferedReader( 15 | new FileReader("big" + charname + ".txt") 16 | ); 17 | String line; 18 | StringBuffer buf = new StringBuffer(); 19 | while ((line = reader.readLine()) != null) { 20 | buf.append(line); 21 | buf.append("\n"); 22 | } 23 | reader.close(); 24 | this.fontdata = buf.toString(); 25 | } catch (IOException e) { 26 | this.fontdata = charname + "?"; 27 | } 28 | } 29 | // 显示大型字符 30 | public void print() { 31 | System.out.print(fontdata); 32 | } 33 | } 34 | -------------------------------------------------------------------------------- /src/Flyweight/A1/BigCharFactory.java: -------------------------------------------------------------------------------- 1 | import java.util.HashMap; 2 | 3 | public class BigCharFactory { 4 | // 管理已经生成的BigChar的实例 5 | private HashMap pool = new HashMap(); 6 | // Singleton模式 7 | private static BigCharFactory singleton = new BigCharFactory(); 8 | // 构造函数 9 | private BigCharFactory() { 10 | } 11 | // 获取唯一的实例 12 | public static BigCharFactory getInstance() { 13 | return singleton; 14 | } 15 | // 生成(共享)BigChar类的实例 16 | public synchronized BigChar getBigChar(char charname) { 17 | BigChar bc = (BigChar)pool.get("" + charname); 18 | if (bc == null) { 19 | bc = new BigChar(charname); // 生成BigChar的实例 20 | pool.put("" + charname, bc); 21 | } 22 | return bc; 23 | } 24 | } 25 | -------------------------------------------------------------------------------- /src/Flyweight/A1/BigString.java: -------------------------------------------------------------------------------- 1 | public class BigString { 2 | // 大型文字的数组 3 | private BigChar[] bigchars; 4 | // 构造函数 5 | public BigString(String string) { 6 | initShared(string); 7 | } 8 | // 构造函数 9 | public BigString(String string, boolean shared) { 10 | if (shared) { 11 | initShared(string); 12 | } else { 13 | initUnshared(string); 14 | } 15 | } 16 | // 共享方式初始化 17 | private void initShared(String string) { 18 | bigchars = new BigChar[string.length()]; 19 | BigCharFactory factory = BigCharFactory.getInstance(); 20 | for (int i = 0; i < bigchars.length; i++) { 21 | bigchars[i] = factory.getBigChar(string.charAt(i)); 22 | } 23 | } 24 | // 非共享方式初始化 25 | private void initUnshared(String string) { 26 | bigchars = new BigChar[string.length()]; 27 | for (int i = 0; i < bigchars.length; i++) { 28 | bigchars[i] = new BigChar(string.charAt(i)); 29 | } 30 | } 31 | // 显示 32 | public void print() { 33 | for (int i = 0; i < bigchars.length; i++) { 34 | bigchars[i].print(); 35 | } 36 | } 37 | } 38 | -------------------------------------------------------------------------------- /src/Flyweight/A1/Main.java: -------------------------------------------------------------------------------- 1 | public class Main { 2 | public static void main(String[] args) { 3 | if (args.length == 0) { 4 | System.out.println("Usage: java Main digits"); 5 | System.out.println("Example: java Main 1212123"); 6 | System.exit(0); 7 | } 8 | BigString bs; 9 | bs = new BigString(args[0], false); // 非共享 10 | bs.print(); 11 | bs = new BigString(args[0], true); // 共享 12 | bs.print(); 13 | } 14 | } 15 | -------------------------------------------------------------------------------- /src/Flyweight/A1/big-.txt: -------------------------------------------------------------------------------- 1 | ................ 2 | ................ 3 | ................ 4 | ................ 5 | ..##########.... 6 | ................ 7 | ................ 8 | ................ 9 | -------------------------------------------------------------------------------- /src/Flyweight/A1/big0.txt: -------------------------------------------------------------------------------- 1 | ....######...... 2 | ..##......##.... 3 | ..##......##.... 4 | ..##......##.... 5 | ..##......##.... 6 | ..##......##.... 7 | ....######...... 8 | ................ 9 | -------------------------------------------------------------------------------- /src/Flyweight/A1/big1.txt: -------------------------------------------------------------------------------- 1 | ......##........ 2 | ..######........ 3 | ......##........ 4 | ......##........ 5 | ......##........ 6 | ......##........ 7 | ..##########.... 8 | ................ 9 | -------------------------------------------------------------------------------- /src/Flyweight/A1/big2.txt: -------------------------------------------------------------------------------- 1 | ....######...... 2 | ..##......##.... 3 | ..........##.... 4 | ......####...... 5 | ....##.......... 6 | ..##............ 7 | ..##########.... 8 | ................ 9 | -------------------------------------------------------------------------------- /src/Flyweight/A1/big3.txt: -------------------------------------------------------------------------------- 1 | ....######...... 2 | ..##......##.... 3 | ..........##.... 4 | ......####...... 5 | ..........##.... 6 | ..##......##.... 7 | ....######...... 8 | ................ 9 | -------------------------------------------------------------------------------- /src/Flyweight/A1/big4.txt: -------------------------------------------------------------------------------- 1 | ........##...... 2 | ......####...... 3 | ....##..##...... 4 | ..##....##...... 5 | ..##########.... 6 | ........##...... 7 | ......######.... 8 | ................ 9 | -------------------------------------------------------------------------------- /src/Flyweight/A1/big5.txt: -------------------------------------------------------------------------------- 1 | ..##########.... 2 | ..##............ 3 | ..##............ 4 | ..########...... 5 | ..........##.... 6 | ..##......##.... 7 | ....######...... 8 | ................ 9 | -------------------------------------------------------------------------------- /src/Flyweight/A1/big6.txt: -------------------------------------------------------------------------------- 1 | ....######...... 2 | ..##......##.... 3 | ..##............ 4 | ..########...... 5 | ..##......##.... 6 | ..##......##.... 7 | ....######...... 8 | ................ 9 | -------------------------------------------------------------------------------- /src/Flyweight/A1/big7.txt: -------------------------------------------------------------------------------- 1 | ..##########.... 2 | ..##......##.... 3 | ..........##.... 4 | ........##...... 5 | ......##........ 6 | ......##........ 7 | ......##........ 8 | ................ 9 | -------------------------------------------------------------------------------- /src/Flyweight/A1/big8.txt: -------------------------------------------------------------------------------- 1 | ....######...... 2 | ..##......##.... 3 | ..##......##.... 4 | ....######...... 5 | ..##......##.... 6 | ..##......##.... 7 | ....######...... 8 | ................ 9 | -------------------------------------------------------------------------------- /src/Flyweight/A1/big9.txt: -------------------------------------------------------------------------------- 1 | ....######...... 2 | ..##......##.... 3 | ..##......##.... 4 | ....########.... 5 | ..........##.... 6 | ..##......##.... 7 | ....######...... 8 | ................ 9 | -------------------------------------------------------------------------------- /src/Flyweight/A2/BigChar.java: -------------------------------------------------------------------------------- 1 | import java.io.BufferedReader; 2 | import java.io.FileReader; 3 | import java.io.IOException; 4 | 5 | public class BigChar { 6 | // 字符名字 7 | private char charname; 8 | // 大型字符对应的字符串(由'#' '.' '\n'组成) 9 | private String fontdata; 10 | // 构造函数 11 | public BigChar(char charname) { 12 | this.charname = charname; 13 | try { 14 | BufferedReader reader = new BufferedReader( 15 | new FileReader("big" + charname + ".txt") 16 | ); 17 | String line; 18 | StringBuffer buf = new StringBuffer(); 19 | while ((line = reader.readLine()) != null) { 20 | buf.append(line); 21 | buf.append("\n"); 22 | } 23 | reader.close(); 24 | this.fontdata = buf.toString(); 25 | } catch (IOException e) { 26 | this.fontdata = charname + "?"; 27 | } 28 | } 29 | // 显示大型字符 30 | public void print() { 31 | System.out.print(fontdata); 32 | } 33 | } 34 | -------------------------------------------------------------------------------- /src/Flyweight/A2/BigCharFactory.java: -------------------------------------------------------------------------------- 1 | import java.util.HashMap; 2 | 3 | public class BigCharFactory { 4 | // 管理已经生成的BigChar的实例 5 | private HashMap pool = new HashMap(); 6 | // Singleton模式 7 | private static BigCharFactory singleton = new BigCharFactory(); 8 | // 构造函数 9 | private BigCharFactory() { 10 | } 11 | // 获取唯一的实例 12 | public static BigCharFactory getInstance() { 13 | return singleton; 14 | } 15 | // 生成(共享)BigChar类的实例 16 | public synchronized BigChar getBigChar(char charname) { 17 | BigChar bc = (BigChar)pool.get("" + charname); 18 | if (bc == null) { 19 | bc = new BigChar(charname); // 生成BigChar的实例 20 | pool.put("" + charname, bc); 21 | } 22 | return bc; 23 | } 24 | } 25 | -------------------------------------------------------------------------------- /src/Flyweight/A2/Main.java: -------------------------------------------------------------------------------- 1 | public class Main { 2 | private static BigString[] bsarray = new BigString[1000]; 3 | public static void main(String[] args) { 4 | System.out.println("共享时:"); 5 | testAllocation(true); 6 | System.out.println("非共享时:"); 7 | testAllocation(false); 8 | } 9 | public static void testAllocation(boolean shared) { 10 | for (int i = 0; i < bsarray.length; i++) { 11 | bsarray[i] = new BigString("1212123", shared); 12 | } 13 | showMemory(); 14 | } 15 | public static void showMemory() { 16 | Runtime.getRuntime().gc(); 17 | long used = Runtime.getRuntime().totalMemory() - Runtime.getRuntime().freeMemory(); 18 | System.out.println("使用内存 = " + used); 19 | } 20 | } 21 | -------------------------------------------------------------------------------- /src/Flyweight/A2/big-.txt: -------------------------------------------------------------------------------- 1 | ................ 2 | ................ 3 | ................ 4 | ................ 5 | ..##########.... 6 | ................ 7 | ................ 8 | ................ 9 | -------------------------------------------------------------------------------- /src/Flyweight/A2/big0.txt: -------------------------------------------------------------------------------- 1 | ....######...... 2 | ..##......##.... 3 | ..##......##.... 4 | ..##......##.... 5 | ..##......##.... 6 | ..##......##.... 7 | ....######...... 8 | ................ 9 | -------------------------------------------------------------------------------- /src/Flyweight/A2/big1.txt: -------------------------------------------------------------------------------- 1 | ......##........ 2 | ..######........ 3 | ......##........ 4 | ......##........ 5 | ......##........ 6 | ......##........ 7 | ..##########.... 8 | ................ 9 | -------------------------------------------------------------------------------- /src/Flyweight/A2/big2.txt: -------------------------------------------------------------------------------- 1 | ....######...... 2 | ..##......##.... 3 | ..........##.... 4 | ......####...... 5 | ....##.......... 6 | ..##............ 7 | ..##########.... 8 | ................ 9 | -------------------------------------------------------------------------------- /src/Flyweight/A2/big3.txt: -------------------------------------------------------------------------------- 1 | ....######...... 2 | ..##......##.... 3 | ..........##.... 4 | ......####...... 5 | ..........##.... 6 | ..##......##.... 7 | ....######...... 8 | ................ 9 | -------------------------------------------------------------------------------- /src/Flyweight/A2/big4.txt: -------------------------------------------------------------------------------- 1 | ........##...... 2 | ......####...... 3 | ....##..##...... 4 | ..##....##...... 5 | ..##########.... 6 | ........##...... 7 | ......######.... 8 | ................ 9 | -------------------------------------------------------------------------------- /src/Flyweight/A2/big5.txt: -------------------------------------------------------------------------------- 1 | ..##########.... 2 | ..##............ 3 | ..##............ 4 | ..########...... 5 | ..........##.... 6 | ..##......##.... 7 | ....######...... 8 | ................ 9 | -------------------------------------------------------------------------------- /src/Flyweight/A2/big6.txt: -------------------------------------------------------------------------------- 1 | ....######...... 2 | ..##......##.... 3 | ..##............ 4 | ..########...... 5 | ..##......##.... 6 | ..##......##.... 7 | ....######...... 8 | ................ 9 | -------------------------------------------------------------------------------- /src/Flyweight/A2/big7.txt: -------------------------------------------------------------------------------- 1 | ..##########.... 2 | ..##......##.... 3 | ..........##.... 4 | ........##...... 5 | ......##........ 6 | ......##........ 7 | ......##........ 8 | ................ 9 | -------------------------------------------------------------------------------- /src/Flyweight/A2/big8.txt: -------------------------------------------------------------------------------- 1 | ....######...... 2 | ..##......##.... 3 | ..##......##.... 4 | ....######...... 5 | ..##......##.... 6 | ..##......##.... 7 | ....######...... 8 | ................ 9 | -------------------------------------------------------------------------------- /src/Flyweight/A2/big9.txt: -------------------------------------------------------------------------------- 1 | ....######...... 2 | ..##......##.... 3 | ..##......##.... 4 | ....########.... 5 | ..........##.... 6 | ..##......##.... 7 | ....######...... 8 | ................ 9 | -------------------------------------------------------------------------------- /src/Flyweight/Sample/BigChar.java: -------------------------------------------------------------------------------- 1 | import java.io.BufferedReader; 2 | import java.io.FileReader; 3 | import java.io.IOException; 4 | 5 | public class BigChar { 6 | // 字符名字 7 | private char charname; 8 | // 大型字符对应的字符串(由'#' '.' '\n'组成) 9 | private String fontdata; 10 | // 构造函数 11 | public BigChar(char charname) { 12 | this.charname = charname; 13 | try { 14 | BufferedReader reader = new BufferedReader( 15 | new FileReader("big" + charname + ".txt") 16 | ); 17 | String line; 18 | StringBuffer buf = new StringBuffer(); 19 | while ((line = reader.readLine()) != null) { 20 | buf.append(line); 21 | buf.append("\n"); 22 | } 23 | reader.close(); 24 | this.fontdata = buf.toString(); 25 | } catch (IOException e) { 26 | this.fontdata = charname + "?"; 27 | } 28 | } 29 | // 显示大型字符 30 | public void print() { 31 | System.out.print(fontdata); 32 | } 33 | } 34 | -------------------------------------------------------------------------------- /src/Flyweight/Sample/BigCharFactory.java: -------------------------------------------------------------------------------- 1 | import java.util.HashMap; 2 | 3 | public class BigCharFactory { 4 | // 管理已经生成的BigChar的实例 5 | private HashMap pool = new HashMap(); 6 | // Singleton模式 7 | private static BigCharFactory singleton = new BigCharFactory(); 8 | // 构造函数 9 | private BigCharFactory() { 10 | } 11 | // 获取唯一的实例 12 | public static BigCharFactory getInstance() { 13 | return singleton; 14 | } 15 | // 生成(共享)BigChar类的实例 16 | public synchronized BigChar getBigChar(char charname) { 17 | BigChar bc = (BigChar)pool.get("" + charname); 18 | if (bc == null) { 19 | bc = new BigChar(charname); // 生成BigChar的实例 20 | pool.put("" + charname, bc); 21 | } 22 | return bc; 23 | } 24 | } 25 | -------------------------------------------------------------------------------- /src/Flyweight/Sample/BigString.java: -------------------------------------------------------------------------------- 1 | public class BigString { 2 | // “大型字符”的数组 3 | private BigChar[] bigchars; 4 | // 构造函数 5 | public BigString(String string) { 6 | bigchars = new BigChar[string.length()]; 7 | BigCharFactory factory = BigCharFactory.getInstance(); 8 | for (int i = 0; i < bigchars.length; i++) { 9 | bigchars[i] = factory.getBigChar(string.charAt(i)); 10 | } 11 | } 12 | // 显示 13 | public void print() { 14 | for (int i = 0; i < bigchars.length; i++) { 15 | bigchars[i].print(); 16 | } 17 | } 18 | } 19 | -------------------------------------------------------------------------------- /src/Flyweight/Sample/Main.java: -------------------------------------------------------------------------------- 1 | public class Main { 2 | public static void main(String[] args) { 3 | if (args.length == 0) { 4 | System.out.println("Usage: java Main digits"); 5 | System.out.println("Example: java Main 1212123"); 6 | System.exit(0); 7 | } 8 | BigString bs = new BigString(args[0]); 9 | bs.print(); 10 | } 11 | } 12 | -------------------------------------------------------------------------------- /src/Flyweight/Sample/big-.txt: -------------------------------------------------------------------------------- 1 | ................ 2 | ................ 3 | ................ 4 | ................ 5 | ..##########.... 6 | ................ 7 | ................ 8 | ................ 9 | -------------------------------------------------------------------------------- /src/Flyweight/Sample/big0.txt: -------------------------------------------------------------------------------- 1 | ....######...... 2 | ..##......##.... 3 | ..##......##.... 4 | ..##......##.... 5 | ..##......##.... 6 | ..##......##.... 7 | ....######...... 8 | ................ 9 | -------------------------------------------------------------------------------- /src/Flyweight/Sample/big1.txt: -------------------------------------------------------------------------------- 1 | ......##........ 2 | ..######........ 3 | ......##........ 4 | ......##........ 5 | ......##........ 6 | ......##........ 7 | ..##########.... 8 | ................ 9 | -------------------------------------------------------------------------------- /src/Flyweight/Sample/big2.txt: -------------------------------------------------------------------------------- 1 | ....######...... 2 | ..##......##.... 3 | ..........##.... 4 | ......####...... 5 | ....##.......... 6 | ..##............ 7 | ..##########.... 8 | ................ 9 | -------------------------------------------------------------------------------- /src/Flyweight/Sample/big3.txt: -------------------------------------------------------------------------------- 1 | ....######...... 2 | ..##......##.... 3 | ..........##.... 4 | ......####...... 5 | ..........##.... 6 | ..##......##.... 7 | ....######...... 8 | ................ 9 | -------------------------------------------------------------------------------- /src/Flyweight/Sample/big4.txt: -------------------------------------------------------------------------------- 1 | ........##...... 2 | ......####...... 3 | ....##..##...... 4 | ..##....##...... 5 | ..##########.... 6 | ........##...... 7 | ......######.... 8 | ................ 9 | -------------------------------------------------------------------------------- /src/Flyweight/Sample/big5.txt: -------------------------------------------------------------------------------- 1 | ..##########.... 2 | ..##............ 3 | ..##............ 4 | ..########...... 5 | ..........##.... 6 | ..##......##.... 7 | ....######...... 8 | ................ 9 | -------------------------------------------------------------------------------- /src/Flyweight/Sample/big6.txt: -------------------------------------------------------------------------------- 1 | ....######...... 2 | ..##......##.... 3 | ..##............ 4 | ..########...... 5 | ..##......##.... 6 | ..##......##.... 7 | ....######...... 8 | ................ 9 | -------------------------------------------------------------------------------- /src/Flyweight/Sample/big7.txt: -------------------------------------------------------------------------------- 1 | ..##########.... 2 | ..##......##.... 3 | ..........##.... 4 | ........##...... 5 | ......##........ 6 | ......##........ 7 | ......##........ 8 | ................ 9 | -------------------------------------------------------------------------------- /src/Flyweight/Sample/big8.txt: -------------------------------------------------------------------------------- 1 | ....######...... 2 | ..##......##.... 3 | ..##......##.... 4 | ....######...... 5 | ..##......##.... 6 | ..##......##.... 7 | ....######...... 8 | ................ 9 | -------------------------------------------------------------------------------- /src/Flyweight/Sample/big9.txt: -------------------------------------------------------------------------------- 1 | ....######...... 2 | ..##......##.... 3 | ..##......##.... 4 | ....########.... 5 | ..........##.... 6 | ..##......##.... 7 | ....######...... 8 | ................ 9 | -------------------------------------------------------------------------------- /src/Interpreter/A1/language/CommandListNode.java: -------------------------------------------------------------------------------- 1 | package language; 2 | 3 | import java.util.*; 4 | 5 | // ::= * end 6 | public class CommandListNode extends Node { 7 | private ArrayList list = new ArrayList(); 8 | public void parse(Context context) throws ParseException { 9 | while (true) { 10 | if (context.currentToken() == null) { 11 | throw new ParseException("Missing 'end'"); 12 | } else if (context.currentToken().equals("end")) { 13 | context.skipToken("end"); 14 | break; 15 | } else { 16 | Node commandNode = new CommandNode(); 17 | commandNode.parse(context); 18 | list.add(commandNode); 19 | } 20 | } 21 | } 22 | public void execute() throws ExecuteException { 23 | Iterator it = list.iterator(); 24 | while (it.hasNext()) { 25 | ((CommandNode)it.next()).execute(); 26 | } 27 | } 28 | public String toString() { 29 | return list.toString(); 30 | } 31 | } 32 | -------------------------------------------------------------------------------- /src/Interpreter/A1/language/CommandNode.java: -------------------------------------------------------------------------------- 1 | package language; 2 | 3 | // ::= | 4 | public class CommandNode extends Node { 5 | private Node node; 6 | public void parse(Context context) throws ParseException { 7 | if (context.currentToken().equals("repeat")) { 8 | node = new RepeatCommandNode(); 9 | node.parse(context); 10 | } else { 11 | node = new PrimitiveCommandNode(); 12 | node.parse(context); 13 | } 14 | } 15 | public void execute() throws ExecuteException { 16 | node.execute(); 17 | } 18 | public String toString() { 19 | return node.toString(); 20 | } 21 | } 22 | -------------------------------------------------------------------------------- /src/Interpreter/A1/language/ExecuteException.java: -------------------------------------------------------------------------------- 1 | package language; 2 | 3 | public class ExecuteException extends Exception { 4 | public ExecuteException(String msg) { 5 | super(msg); 6 | } 7 | } 8 | -------------------------------------------------------------------------------- /src/Interpreter/A1/language/Executor.java: -------------------------------------------------------------------------------- 1 | package language; 2 | 3 | public interface Executor { 4 | public abstract void execute() throws ExecuteException; 5 | } 6 | -------------------------------------------------------------------------------- /src/Interpreter/A1/language/ExecutorFactory.java: -------------------------------------------------------------------------------- 1 | package language; 2 | 3 | public interface ExecutorFactory { 4 | public abstract Executor createExecutor(String name); 5 | } 6 | -------------------------------------------------------------------------------- /src/Interpreter/A1/language/InterpreterFacade.java: -------------------------------------------------------------------------------- 1 | package language; 2 | 3 | public class InterpreterFacade implements Executor { 4 | private ExecutorFactory factory; 5 | private Context context; 6 | private Node programNode; 7 | public InterpreterFacade(ExecutorFactory factory) { 8 | this.factory = factory; 9 | } 10 | public boolean parse(String text) { 11 | boolean ok = true; 12 | this.context = new Context(text); 13 | this.context.setExecutorFactory(factory); 14 | this.programNode = new ProgramNode(); 15 | try { 16 | programNode.parse(context); 17 | System.out.println(programNode.toString()); 18 | } catch (ParseException e) { 19 | e.printStackTrace(); 20 | ok = false; 21 | } 22 | return ok; 23 | } 24 | public void execute() throws ExecuteException { 25 | try { 26 | programNode.execute(); 27 | } catch (ExecuteException e) { 28 | e.printStackTrace(); 29 | } 30 | } 31 | } 32 | -------------------------------------------------------------------------------- /src/Interpreter/A1/language/Node.java: -------------------------------------------------------------------------------- 1 | package language; 2 | 3 | public abstract class Node implements Executor { 4 | public abstract void parse(Context context) throws ParseException; 5 | } 6 | -------------------------------------------------------------------------------- /src/Interpreter/A1/language/ParseException.java: -------------------------------------------------------------------------------- 1 | package language; 2 | 3 | public class ParseException extends Exception { 4 | public ParseException(String msg) { 5 | super(msg); 6 | } 7 | } 8 | -------------------------------------------------------------------------------- /src/Interpreter/A1/language/PrimitiveCommandNode.java: -------------------------------------------------------------------------------- 1 | package language; 2 | 3 | // ::= go | right | left 4 | public class PrimitiveCommandNode extends Node { 5 | private String name; 6 | private Executor executor; 7 | public void parse(Context context) throws ParseException { 8 | name = context.currentToken(); 9 | context.skipToken(name); 10 | executor = context.createExecutor(name); 11 | } 12 | public void execute() throws ExecuteException { 13 | if (executor == null) { 14 | throw new ExecuteException(name + ": is not defined"); 15 | } else { 16 | executor.execute(); 17 | } 18 | } 19 | public String toString() { 20 | return name; 21 | } 22 | } 23 | -------------------------------------------------------------------------------- /src/Interpreter/A1/language/ProgramNode.java: -------------------------------------------------------------------------------- 1 | package language; 2 | 3 | // ::= program 4 | public class ProgramNode extends Node { 5 | private Node commandListNode; 6 | public void parse(Context context) throws ParseException { 7 | context.skipToken("program"); 8 | commandListNode = new CommandListNode(); 9 | commandListNode.parse(context); 10 | } 11 | public void execute() throws ExecuteException { 12 | commandListNode.execute(); 13 | } 14 | public String toString() { 15 | return "[program " + commandListNode + "]"; 16 | } 17 | } 18 | -------------------------------------------------------------------------------- /src/Interpreter/A1/language/RepeatCommandNode.java: -------------------------------------------------------------------------------- 1 | package language; 2 | 3 | // ::= repeat 4 | public class RepeatCommandNode extends Node { 5 | private int number; 6 | private Node commandListNode; 7 | public void parse(Context context) throws ParseException { 8 | context.skipToken("repeat"); 9 | number = context.currentNumber(); 10 | context.nextToken(); 11 | commandListNode = new CommandListNode(); 12 | commandListNode.parse(context); 13 | } 14 | public void execute() throws ExecuteException { 15 | for (int i = 0; i < number; i++) { 16 | commandListNode.execute(); 17 | } 18 | } 19 | public String toString() { 20 | return "[repeat " + number + " " + commandListNode + "]"; 21 | } 22 | } 23 | -------------------------------------------------------------------------------- /src/Interpreter/Sample/CommandListNode.java: -------------------------------------------------------------------------------- 1 | import java.util.ArrayList; 2 | 3 | // ::= * end 4 | public class CommandListNode extends Node { 5 | private ArrayList list = new ArrayList(); 6 | public void parse(Context context) throws ParseException { 7 | while (true) { 8 | if (context.currentToken() == null) { 9 | throw new ParseException("Missing 'end'"); 10 | } else if (context.currentToken().equals("end")) { 11 | context.skipToken("end"); 12 | break; 13 | } else { 14 | Node commandNode = new CommandNode(); 15 | commandNode.parse(context); 16 | list.add(commandNode); 17 | } 18 | } 19 | } 20 | public String toString() { 21 | return list.toString(); 22 | } 23 | } 24 | -------------------------------------------------------------------------------- /src/Interpreter/Sample/CommandNode.java: -------------------------------------------------------------------------------- 1 | // ::= | 2 | public class CommandNode extends Node { 3 | private Node node; 4 | public void parse(Context context) throws ParseException { 5 | if (context.currentToken().equals("repeat")) { 6 | node = new RepeatCommandNode(); 7 | node.parse(context); 8 | } else { 9 | node = new PrimitiveCommandNode(); 10 | node.parse(context); 11 | } 12 | } 13 | public String toString() { 14 | return node.toString(); 15 | } 16 | } 17 | -------------------------------------------------------------------------------- /src/Interpreter/Sample/Main.java: -------------------------------------------------------------------------------- 1 | import java.util.*; 2 | import java.io.*; 3 | 4 | public class Main { 5 | public static void main(String[] args) { 6 | try { 7 | BufferedReader reader = new BufferedReader(new FileReader("program.txt")); 8 | String text; 9 | while ((text = reader.readLine()) != null) { 10 | System.out.println("text = \"" + text + "\""); 11 | Node node = new ProgramNode(); 12 | node.parse(new Context(text)); 13 | System.out.println("node = " + node); 14 | } 15 | } catch (Exception e) { 16 | e.printStackTrace(); 17 | } 18 | } 19 | } 20 | -------------------------------------------------------------------------------- /src/Interpreter/Sample/Node.java: -------------------------------------------------------------------------------- 1 | public abstract class Node { 2 | public abstract void parse(Context context) throws ParseException; 3 | } 4 | -------------------------------------------------------------------------------- /src/Interpreter/Sample/ParseException.java: -------------------------------------------------------------------------------- 1 | public class ParseException extends Exception { 2 | public ParseException(String msg) { 3 | super(msg); 4 | } 5 | } 6 | -------------------------------------------------------------------------------- /src/Interpreter/Sample/PrimitiveCommandNode.java: -------------------------------------------------------------------------------- 1 | // ::= go | right | left 2 | public class PrimitiveCommandNode extends Node { 3 | private String name; 4 | public void parse(Context context) throws ParseException { 5 | name = context.currentToken(); 6 | context.skipToken(name); 7 | if (!name.equals("go") && !name.equals("right") && !name.equals("left")) { 8 | throw new ParseException(name + " is undefined"); 9 | } 10 | } 11 | public String toString() { 12 | return name; 13 | } 14 | } 15 | -------------------------------------------------------------------------------- /src/Interpreter/Sample/ProgramNode.java: -------------------------------------------------------------------------------- 1 | // ::= program 2 | public class ProgramNode extends Node { 3 | private Node commandListNode; 4 | public void parse(Context context) throws ParseException { 5 | context.skipToken("program"); 6 | commandListNode = new CommandListNode(); 7 | commandListNode.parse(context); 8 | } 9 | public String toString() { 10 | return "[program " + commandListNode + "]"; 11 | } 12 | } 13 | -------------------------------------------------------------------------------- /src/Interpreter/Sample/RepeatCommandNode.java: -------------------------------------------------------------------------------- 1 | // ::= repeat 2 | public class RepeatCommandNode extends Node { 3 | private int number; 4 | private Node commandListNode; 5 | public void parse(Context context) throws ParseException { 6 | context.skipToken("repeat"); 7 | number = context.currentNumber(); 8 | context.nextToken(); 9 | commandListNode = new CommandListNode(); 10 | commandListNode.parse(context); 11 | } 12 | public String toString() { 13 | return "[repeat " + number + " " + commandListNode + "]"; 14 | } 15 | } 16 | -------------------------------------------------------------------------------- /src/Interpreter/Sample/program.txt: -------------------------------------------------------------------------------- 1 | program end 2 | program go end 3 | program go right go right go right go right end 4 | program repeat 4 go right end end 5 | program repeat 4 repeat 3 go right go left end right end end 6 | -------------------------------------------------------------------------------- /src/Iterator/A1/Aggregate.java: -------------------------------------------------------------------------------- 1 | public interface Aggregate { 2 | public abstract Iterator iterator(); 3 | } 4 | -------------------------------------------------------------------------------- /src/Iterator/A1/Book.java: -------------------------------------------------------------------------------- 1 | public class Book { 2 | private String name; 3 | public Book(String name) { 4 | this.name = name; 5 | } 6 | public String getName() { 7 | return name; 8 | } 9 | } 10 | -------------------------------------------------------------------------------- /src/Iterator/A1/BookShelf.java: -------------------------------------------------------------------------------- 1 | import java.util.ArrayList; 2 | 3 | public class BookShelf implements Aggregate { 4 | private ArrayList books; 5 | public BookShelf(int initialsize) { 6 | this.books = new ArrayList(initialsize); 7 | } 8 | public Book getBookAt(int index) { 9 | return (Book)books.get(index); 10 | } 11 | public void appendBook(Book book) { 12 | books.add(book); 13 | } 14 | public int getLength() { 15 | return books.size(); 16 | } 17 | public Iterator iterator() { 18 | return new BookShelfIterator(this); 19 | } 20 | } 21 | -------------------------------------------------------------------------------- /src/Iterator/A1/BookShelfIterator.java: -------------------------------------------------------------------------------- 1 | public class BookShelfIterator implements Iterator { 2 | private BookShelf bookShelf; 3 | private int index; 4 | public BookShelfIterator(BookShelf bookShelf) { 5 | this.bookShelf = bookShelf; 6 | this.index = 0; 7 | } 8 | public boolean hasNext() { 9 | if (index < bookShelf.getLength()) { 10 | return true; 11 | } else { 12 | return false; 13 | } 14 | } 15 | public Object next() { 16 | Book book = bookShelf.getBookAt(index); 17 | index++; 18 | return book; 19 | } 20 | } 21 | -------------------------------------------------------------------------------- /src/Iterator/A1/Iterator.java: -------------------------------------------------------------------------------- 1 | public interface Iterator { 2 | public abstract boolean hasNext(); 3 | public abstract Object next(); 4 | } 5 | -------------------------------------------------------------------------------- /src/Iterator/A1/Main.java: -------------------------------------------------------------------------------- 1 | import java.util.*; 2 | 3 | public class Main { 4 | public static void main(String[] args) { 5 | BookShelf bookShelf = new BookShelf(4); 6 | bookShelf.appendBook(new Book("Around the World in 80 Days")); 7 | bookShelf.appendBook(new Book("Bible")); 8 | bookShelf.appendBook(new Book("Cinderella")); 9 | bookShelf.appendBook(new Book("Daddy-Long-Legs")); 10 | bookShelf.appendBook(new Book("East of Eden")); 11 | bookShelf.appendBook(new Book("Frankenstein")); 12 | bookShelf.appendBook(new Book("Gulliver's Travels")); 13 | bookShelf.appendBook(new Book("Hamlet")); 14 | Iterator it = bookShelf.iterator(); 15 | while (it.hasNext()) { 16 | Book book = (Book)it.next(); 17 | System.out.println(book.getName()); 18 | } 19 | } 20 | } 21 | -------------------------------------------------------------------------------- /src/Iterator/Sample/Aggregate.java: -------------------------------------------------------------------------------- 1 | public interface Aggregate { 2 | public abstract Iterator iterator(); 3 | } 4 | -------------------------------------------------------------------------------- /src/Iterator/Sample/Book.java: -------------------------------------------------------------------------------- 1 | public class Book { 2 | private String name; 3 | public Book(String name) { 4 | this.name = name; 5 | } 6 | public String getName() { 7 | return name; 8 | } 9 | } 10 | -------------------------------------------------------------------------------- /src/Iterator/Sample/BookShelf.java: -------------------------------------------------------------------------------- 1 | public class BookShelf implements Aggregate { 2 | private Book[] books; 3 | private int last = 0; 4 | public BookShelf(int maxsize) { 5 | this.books = new Book[maxsize]; 6 | } 7 | public Book getBookAt(int index) { 8 | return books[index]; 9 | } 10 | public void appendBook(Book book) { 11 | this.books[last] = book; 12 | last++; 13 | } 14 | public int getLength() { 15 | return last; 16 | } 17 | public Iterator iterator() { 18 | return new BookShelfIterator(this); 19 | } 20 | } 21 | -------------------------------------------------------------------------------- /src/Iterator/Sample/BookShelfIterator.java: -------------------------------------------------------------------------------- 1 | public class BookShelfIterator implements Iterator { 2 | private BookShelf bookShelf; 3 | private int index; 4 | public BookShelfIterator(BookShelf bookShelf) { 5 | this.bookShelf = bookShelf; 6 | this.index = 0; 7 | } 8 | public boolean hasNext() { 9 | if (index < bookShelf.getLength()) { 10 | return true; 11 | } else { 12 | return false; 13 | } 14 | } 15 | public Object next() { 16 | Book book = bookShelf.getBookAt(index); 17 | index++; 18 | return book; 19 | } 20 | } 21 | -------------------------------------------------------------------------------- /src/Iterator/Sample/Iterator.java: -------------------------------------------------------------------------------- 1 | public interface Iterator { 2 | public abstract boolean hasNext(); 3 | public abstract Object next(); 4 | } 5 | -------------------------------------------------------------------------------- /src/Iterator/Sample/Main.java: -------------------------------------------------------------------------------- 1 | import java.util.*; 2 | 3 | public class Main { 4 | public static void main(String[] args) { 5 | BookShelf bookShelf = new BookShelf(4); 6 | bookShelf.appendBook(new Book("Around the World in 80 Days")); 7 | bookShelf.appendBook(new Book("Bible")); 8 | bookShelf.appendBook(new Book("Cinderella")); 9 | bookShelf.appendBook(new Book("Daddy-Long-Legs")); 10 | Iterator it = bookShelf.iterator(); 11 | while (it.hasNext()) { 12 | Book book = (Book)it.next(); 13 | System.out.println(book.getName()); 14 | } 15 | } 16 | } 17 | -------------------------------------------------------------------------------- /src/Mediator/A1/Colleague.java: -------------------------------------------------------------------------------- 1 | public interface Colleague { 2 | public abstract void setMediator(Mediator mediator); 3 | public abstract void setColleagueEnabled(boolean enabled); 4 | } 5 | -------------------------------------------------------------------------------- /src/Mediator/A1/ColleagueButton.java: -------------------------------------------------------------------------------- 1 | import java.awt.Button; 2 | 3 | public class ColleagueButton extends Button implements Colleague { 4 | private Mediator mediator; 5 | public ColleagueButton(String caption) { 6 | super(caption); 7 | } 8 | public void setMediator(Mediator mediator) { // 保存Mediator 9 | this.mediator = mediator; 10 | } 11 | public void setColleagueEnabled(boolean enabled) { // Mediator下达启用/禁用的指示 12 | setEnabled(enabled); 13 | } 14 | } 15 | -------------------------------------------------------------------------------- /src/Mediator/A1/ColleagueCheckbox.java: -------------------------------------------------------------------------------- 1 | import java.awt.Checkbox; 2 | import java.awt.CheckboxGroup; 3 | import java.awt.event.ItemListener; 4 | import java.awt.event.ItemEvent; 5 | 6 | public class ColleagueCheckbox extends Checkbox implements ItemListener, Colleague { 7 | private Mediator mediator; 8 | public ColleagueCheckbox(String caption, CheckboxGroup group, boolean state) { // 构造函数 9 | super(caption, group, state); 10 | } 11 | public void setMediator(Mediator mediator) { // 保存Mediator 12 | this.mediator = mediator; 13 | } 14 | public void setColleagueEnabled(boolean enabled) { // Mediator下达启用/禁用指示 15 | setEnabled(enabled); 16 | } 17 | public void itemStateChanged(ItemEvent e) { // 当状态发生变化时通知Mediator 18 | mediator.colleagueChanged(); 19 | } 20 | } 21 | -------------------------------------------------------------------------------- /src/Mediator/A1/ColleagueTextField.java: -------------------------------------------------------------------------------- 1 | import java.awt.TextField; 2 | import java.awt.Color; 3 | import java.awt.event.TextListener; 4 | import java.awt.event.TextEvent; 5 | 6 | public class ColleagueTextField extends TextField implements TextListener, Colleague { 7 | private Mediator mediator; 8 | public ColleagueTextField(String text, int columns) { // 构造函数 9 | super(text, columns); 10 | } 11 | public void setMediator(Mediator mediator) { // 保存Mediator 12 | this.mediator = mediator; 13 | } 14 | public void setColleagueEnabled(boolean enabled) { // Mediator下达启用/禁用的指示 15 | setEnabled(enabled); 16 | setBackground(enabled ? Color.white : Color.lightGray); 17 | } 18 | public void textValueChanged(TextEvent e) { // 当文字发生变化时通知Mediator 19 | mediator.colleagueChanged(); 20 | } 21 | } 22 | -------------------------------------------------------------------------------- /src/Mediator/A1/Main.java: -------------------------------------------------------------------------------- 1 | import java.awt.*; 2 | import java.awt.event.*; 3 | 4 | public class Main { 5 | static public void main(String args[]) { 6 | new LoginFrame("Mediator Sample"); 7 | } 8 | } 9 | -------------------------------------------------------------------------------- /src/Mediator/A1/Mediator.java: -------------------------------------------------------------------------------- 1 | public interface Mediator { 2 | public abstract void createColleagues(); 3 | public abstract void colleagueChanged(); 4 | } 5 | -------------------------------------------------------------------------------- /src/Mediator/Sample/Colleague.java: -------------------------------------------------------------------------------- 1 | public interface Colleague { 2 | public abstract void setMediator(Mediator mediator); 3 | public abstract void setColleagueEnabled(boolean enabled); 4 | } 5 | -------------------------------------------------------------------------------- /src/Mediator/Sample/ColleagueButton.java: -------------------------------------------------------------------------------- 1 | import java.awt.Button; 2 | 3 | public class ColleagueButton extends Button implements Colleague { 4 | private Mediator mediator; 5 | public ColleagueButton(String caption) { 6 | super(caption); 7 | } 8 | public void setMediator(Mediator mediator) { // 保存Mediator 9 | this.mediator = mediator; 10 | } 11 | public void setColleagueEnabled(boolean enabled) { // Mediator下达启用/禁用的指示 12 | setEnabled(enabled); 13 | } 14 | } 15 | -------------------------------------------------------------------------------- /src/Mediator/Sample/ColleagueCheckbox.java: -------------------------------------------------------------------------------- 1 | import java.awt.Checkbox; 2 | import java.awt.CheckboxGroup; 3 | import java.awt.event.ItemListener; 4 | import java.awt.event.ItemEvent; 5 | 6 | public class ColleagueCheckbox extends Checkbox implements ItemListener, Colleague { 7 | private Mediator mediator; 8 | public ColleagueCheckbox(String caption, CheckboxGroup group, boolean state) { // 构造函数 9 | super(caption, group, state); 10 | } 11 | public void setMediator(Mediator mediator) { // 保存Mediator 12 | this.mediator = mediator; 13 | } 14 | public void setColleagueEnabled(boolean enabled) { // Mediator下达启用/禁用指示 15 | setEnabled(enabled); 16 | } 17 | public void itemStateChanged(ItemEvent e) { // 当状态发生变化时通知Mediator 18 | mediator.colleagueChanged(); 19 | } 20 | } 21 | -------------------------------------------------------------------------------- /src/Mediator/Sample/ColleagueTextField.java: -------------------------------------------------------------------------------- 1 | import java.awt.TextField; 2 | import java.awt.Color; 3 | import java.awt.event.TextListener; 4 | import java.awt.event.TextEvent; 5 | 6 | public class ColleagueTextField extends TextField implements TextListener, Colleague { 7 | private Mediator mediator; 8 | public ColleagueTextField(String text, int columns) { // 构造函数 9 | super(text, columns); 10 | } 11 | public void setMediator(Mediator mediator) { // 保存Mediator 12 | this.mediator = mediator; 13 | } 14 | public void setColleagueEnabled(boolean enabled) { // Mediator下达启用/禁用的指示 15 | setEnabled(enabled); 16 | setBackground(enabled ? Color.white : Color.lightGray); 17 | } 18 | public void textValueChanged(TextEvent e) { // 当文字发生变化时通知Mediator 19 | mediator.colleagueChanged(); 20 | } 21 | } 22 | -------------------------------------------------------------------------------- /src/Mediator/Sample/Main.java: -------------------------------------------------------------------------------- 1 | import java.awt.*; 2 | import java.awt.event.*; 3 | 4 | public class Main { 5 | static public void main(String args[]) { 6 | new LoginFrame("Mediator Sample"); 7 | } 8 | } 9 | -------------------------------------------------------------------------------- /src/Mediator/Sample/Mediator.java: -------------------------------------------------------------------------------- 1 | public interface Mediator { 2 | public abstract void createColleagues(); 3 | public abstract void colleagueChanged(); 4 | } 5 | -------------------------------------------------------------------------------- /src/Memento/A4/game/Memento.java: -------------------------------------------------------------------------------- 1 | package game; 2 | import java.io.*; 3 | import java.util.*; 4 | 5 | public class Memento implements Serializable { 6 | int money; // 所持金钱 7 | ArrayList fruits; // 获得的水果 8 | public int getMoney() { // 获取现在所持金钱(narrow interface) 9 | return money; 10 | } 11 | Memento(int money) { // 构造函数(wide interface) 12 | this.money = money; 13 | this.fruits = new ArrayList(); 14 | } 15 | void addFruit(String fruit) { // 赢得水果(wide interface) 16 | fruits.add(fruit); 17 | } 18 | List getFruits() { // 获取水果(wide interface) 19 | return (List)fruits.clone(); 20 | } 21 | } 22 | -------------------------------------------------------------------------------- /src/Memento/Sample/game/Memento.java: -------------------------------------------------------------------------------- 1 | package game; 2 | import java.util.*; 3 | 4 | public class Memento { 5 | int money; // 所持金钱 6 | ArrayList fruits; // 当前获得的水果 7 | public int getMoney() { // 获取当前所持金钱(narrow interface) 8 | return money; 9 | } 10 | Memento(int money) { // 构造函数(wide interface) 11 | this.money = money; 12 | this.fruits = new ArrayList(); 13 | } 14 | void addFruit(String fruit) { // 添加水果(wide interface) 15 | fruits.add(fruit); 16 | } 17 | List getFruits() { // 获取当前所持所有水果(wide interface) 18 | return (List)fruits.clone(); 19 | } 20 | } 21 | -------------------------------------------------------------------------------- /src/Observer/A1/DigitObserver.java: -------------------------------------------------------------------------------- 1 | public class DigitObserver implements Observer { 2 | public void update(NumberGenerator generator) { 3 | System.out.println("DigitObserver:" + generator.getNumber()); 4 | try { 5 | Thread.sleep(100); 6 | } catch (InterruptedException e) { 7 | } 8 | } 9 | } 10 | -------------------------------------------------------------------------------- /src/Observer/A1/GraphObserver.java: -------------------------------------------------------------------------------- 1 | public class GraphObserver implements Observer { 2 | public void update(NumberGenerator generator) { 3 | System.out.print("GraphObserver:"); 4 | int count = generator.getNumber(); 5 | for (int i = 0; i < count; i++) { 6 | System.out.print("*"); 7 | } 8 | System.out.println(""); 9 | try { 10 | Thread.sleep(100); 11 | } catch (InterruptedException e) { 12 | } 13 | } 14 | } 15 | -------------------------------------------------------------------------------- /src/Observer/A1/IncrementalNumberGenerator.java: -------------------------------------------------------------------------------- 1 | public class IncrementalNumberGenerator extends NumberGenerator { 2 | private int number; // 当前数值 3 | private int end; // 结束数值(不包含该值) 4 | private int inc; // 递增步长 5 | public IncrementalNumberGenerator(int start, int end, int inc) { 6 | this.number = start; 7 | this.end = end; 8 | this.inc = inc; 9 | } 10 | public int getNumber() { // 获取当前数值 11 | return number; 12 | } 13 | public void execute() { 14 | while (number < end) { 15 | notifyObservers(); 16 | number += inc; 17 | } 18 | } 19 | } 20 | -------------------------------------------------------------------------------- /src/Observer/A1/Main.java: -------------------------------------------------------------------------------- 1 | public class Main { 2 | public static void main(String[] args) { 3 | NumberGenerator generator = new IncrementalNumberGenerator(10, 50, 5); 4 | Observer observer1 = new DigitObserver(); 5 | Observer observer2 = new GraphObserver(); 6 | generator.addObserver(observer1); 7 | generator.addObserver(observer2); 8 | generator.execute(); 9 | } 10 | } 11 | -------------------------------------------------------------------------------- /src/Observer/A1/NumberGenerator.java: -------------------------------------------------------------------------------- 1 | import java.util.ArrayList; 2 | import java.util.Iterator; 3 | 4 | public abstract class NumberGenerator { 5 | private ArrayList observers = new ArrayList(); // 保存Observer们 6 | public void addObserver(Observer observer) { // 注册Observer 7 | observers.add(observer); 8 | } 9 | public void deleteObserver(Observer observer) { // 删除Observer 10 | observers.remove(observer); 11 | } 12 | public void notifyObservers() { // 向Observer发送通知 13 | Iterator it = observers.iterator(); 14 | while (it.hasNext()) { 15 | Observer o = (Observer)it.next(); 16 | o.update(this); 17 | } 18 | } 19 | public abstract int getNumber(); // 获取数值 20 | public abstract void execute(); // 生成数值 21 | } 22 | -------------------------------------------------------------------------------- /src/Observer/A1/Observer.java: -------------------------------------------------------------------------------- 1 | public interface Observer { 2 | public abstract void update(NumberGenerator generator); 3 | } 4 | -------------------------------------------------------------------------------- /src/Observer/A1/RandomNumberGenerator.java: -------------------------------------------------------------------------------- 1 | import java.util.Random; 2 | 3 | public class RandomNumberGenerator extends NumberGenerator { 4 | private Random random = new Random(); // 随机数生成器 5 | private int number; // 当前数值 6 | public int getNumber() { // 获取当前数值 7 | return number; 8 | } 9 | public void execute() { 10 | for (int i = 0; i < 20; i++) { 11 | number = random.nextInt(50); 12 | notifyObservers(); 13 | } 14 | } 15 | } 16 | -------------------------------------------------------------------------------- /src/Observer/A2/DigitObserver.java: -------------------------------------------------------------------------------- 1 | public class DigitObserver implements Observer { 2 | public void update(NumberGenerator generator) { 3 | System.out.println("DigitObserver:" + generator.getNumber()); 4 | try { 5 | Thread.sleep(100); 6 | } catch (InterruptedException e) { 7 | } 8 | } 9 | } 10 | -------------------------------------------------------------------------------- /src/Observer/A2/GraphObserver.java: -------------------------------------------------------------------------------- 1 | public class GraphObserver implements Observer { 2 | public void update(NumberGenerator generator) { 3 | System.out.print("GraphObserver:"); 4 | int count = generator.getNumber(); 5 | for (int i = 0; i < count; i++) { 6 | System.out.print("*"); 7 | } 8 | System.out.println(""); 9 | try { 10 | Thread.sleep(100); 11 | } catch (InterruptedException e) { 12 | } 13 | } 14 | } 15 | -------------------------------------------------------------------------------- /src/Observer/A2/Main.java: -------------------------------------------------------------------------------- 1 | public class Main { 2 | public static void main(String[] args) { 3 | NumberGenerator generator = new RandomNumberGenerator(); 4 | Observer observer1 = new DigitObserver(); 5 | Observer observer2 = new GraphObserver(); 6 | Observer observer3 = new FrameObserver(); 7 | generator.addObserver(observer1); 8 | generator.addObserver(observer2); 9 | generator.addObserver(observer3); 10 | generator.execute(); 11 | } 12 | } 13 | -------------------------------------------------------------------------------- /src/Observer/A2/NumberGenerator.java: -------------------------------------------------------------------------------- 1 | import java.util.ArrayList; 2 | import java.util.Iterator; 3 | 4 | public abstract class NumberGenerator { 5 | private ArrayList observers = new ArrayList(); // 保存Observer们 6 | public void addObserver(Observer observer) { // 注册Observer 7 | observers.add(observer); 8 | } 9 | public void deleteObserver(Observer observer) { // 删除Observer 10 | observers.remove(observer); 11 | } 12 | public void notifyObservers() { // 向Observer发送通知 13 | Iterator it = observers.iterator(); 14 | while (it.hasNext()) { 15 | Observer o = (Observer)it.next(); 16 | o.update(this); 17 | } 18 | } 19 | public abstract int getNumber(); // 获取数值 20 | public abstract void execute(); // 生成数值 21 | } 22 | -------------------------------------------------------------------------------- /src/Observer/A2/Observer.java: -------------------------------------------------------------------------------- 1 | public interface Observer { 2 | public abstract void update(NumberGenerator generator); 3 | } 4 | -------------------------------------------------------------------------------- /src/Observer/A2/RandomNumberGenerator.java: -------------------------------------------------------------------------------- 1 | import java.util.Random; 2 | 3 | public class RandomNumberGenerator extends NumberGenerator { 4 | private Random random = new Random(); // 随机数生成器 5 | private int number; // 当前数值 6 | public int getNumber() { // 获取当前数值 7 | return number; 8 | } 9 | public void execute() { 10 | for (int i = 0; i < 20; i++) { 11 | number = random.nextInt(50); 12 | notifyObservers(); 13 | } 14 | } 15 | } 16 | -------------------------------------------------------------------------------- /src/Observer/Q1/Main.java: -------------------------------------------------------------------------------- 1 | public class Main { 2 | public static void main(String[] args) { 3 | NumberGenerator generator = new IncrementalNumberGenerator(10, 50, 5); 4 | Observer observer1 = new DigitObserver(); 5 | Observer observer2 = new GraphObserver(); 6 | generator.addObserver(observer1); 7 | generator.addObserver(observer2); 8 | generator.execute(); 9 | } 10 | } 11 | -------------------------------------------------------------------------------- /src/Observer/Sample/DigitObserver.java: -------------------------------------------------------------------------------- 1 | public class DigitObserver implements Observer { 2 | public void update(NumberGenerator generator) { 3 | System.out.println("DigitObserver:" + generator.getNumber()); 4 | try { 5 | Thread.sleep(100); 6 | } catch (InterruptedException e) { 7 | } 8 | } 9 | } 10 | -------------------------------------------------------------------------------- /src/Observer/Sample/GraphObserver.java: -------------------------------------------------------------------------------- 1 | public class GraphObserver implements Observer { 2 | public void update(NumberGenerator generator) { 3 | System.out.print("GraphObserver:"); 4 | int count = generator.getNumber(); 5 | for (int i = 0; i < count; i++) { 6 | System.out.print("*"); 7 | } 8 | System.out.println(""); 9 | try { 10 | Thread.sleep(100); 11 | } catch (InterruptedException e) { 12 | } 13 | } 14 | } 15 | -------------------------------------------------------------------------------- /src/Observer/Sample/Main.java: -------------------------------------------------------------------------------- 1 | public class Main { 2 | public static void main(String[] args) { 3 | NumberGenerator generator = new RandomNumberGenerator(); 4 | Observer observer1 = new DigitObserver(); 5 | Observer observer2 = new GraphObserver(); 6 | generator.addObserver(observer1); 7 | generator.addObserver(observer2); 8 | generator.execute(); 9 | } 10 | } 11 | -------------------------------------------------------------------------------- /src/Observer/Sample/NumberGenerator.java: -------------------------------------------------------------------------------- 1 | import java.util.ArrayList; 2 | import java.util.Iterator; 3 | 4 | public abstract class NumberGenerator { 5 | private ArrayList observers = new ArrayList(); // 保存Observer们 6 | public void addObserver(Observer observer) { // 注册Observer 7 | observers.add(observer); 8 | } 9 | public void deleteObserver(Observer observer) { // 删除Observer 10 | observers.remove(observer); 11 | } 12 | public void notifyObservers() { // 向Observer发送通知 13 | Iterator it = observers.iterator(); 14 | while (it.hasNext()) { 15 | Observer o = (Observer)it.next(); 16 | o.update(this); 17 | } 18 | } 19 | public abstract int getNumber(); // 获取数值 20 | public abstract void execute(); // 生成数值 21 | } 22 | -------------------------------------------------------------------------------- /src/Observer/Sample/Observer.java: -------------------------------------------------------------------------------- 1 | public interface Observer { 2 | public abstract void update(NumberGenerator generator); 3 | } 4 | -------------------------------------------------------------------------------- /src/Observer/Sample/RandomNumberGenerator.java: -------------------------------------------------------------------------------- 1 | import java.util.Random; 2 | 3 | public class RandomNumberGenerator extends NumberGenerator { 4 | private Random random = new Random(); // 随机数生成器 5 | private int number; // 当前数值 6 | public int getNumber() { // 获取当前数值 7 | return number; 8 | } 9 | public void execute() { 10 | for (int i = 0; i < 20; i++) { 11 | number = random.nextInt(50); 12 | notifyObservers(); 13 | } 14 | } 15 | } 16 | -------------------------------------------------------------------------------- /src/Prototype/Sample/Main.java: -------------------------------------------------------------------------------- 1 | import framework.*; 2 | 3 | public class Main { 4 | public static void main(String[] args) { 5 | // 准备 6 | Manager manager = new Manager(); 7 | UnderlinePen upen = new UnderlinePen('~'); 8 | MessageBox mbox = new MessageBox('*'); 9 | MessageBox sbox = new MessageBox('/'); 10 | manager.register("strong message", upen); 11 | manager.register("warning box", mbox); 12 | manager.register("slash box", sbox); 13 | 14 | // 生成 15 | Product p1 = manager.create("strong message"); 16 | p1.use("Hello, world."); 17 | Product p2 = manager.create("warning box"); 18 | p2.use("Hello, world."); 19 | Product p3 = manager.create("slash box"); 20 | p3.use("Hello, world."); 21 | } 22 | } 23 | -------------------------------------------------------------------------------- /src/Prototype/Sample/MessageBox.java: -------------------------------------------------------------------------------- 1 | import framework.*; 2 | 3 | public class MessageBox implements Product { 4 | private char decochar; 5 | public MessageBox(char decochar) { 6 | this.decochar = decochar; 7 | } 8 | public void use(String s) { 9 | int length = s.getBytes().length; 10 | for (int i = 0; i < length + 4; i++) { 11 | System.out.print(decochar); 12 | } 13 | System.out.println(""); 14 | System.out.println(decochar + " " + s + " " + decochar); 15 | for (int i = 0; i < length + 4; i++) { 16 | System.out.print(decochar); 17 | } 18 | System.out.println(""); 19 | } 20 | public Product createClone() { 21 | Product p = null; 22 | try { 23 | p = (Product)clone(); 24 | } catch (CloneNotSupportedException e) { 25 | e.printStackTrace(); 26 | } 27 | return p; 28 | } 29 | } 30 | -------------------------------------------------------------------------------- /src/Prototype/Sample/UnderlinePen.java: -------------------------------------------------------------------------------- 1 | import framework.*; 2 | 3 | public class UnderlinePen implements Product { 4 | private char ulchar; 5 | public UnderlinePen(char ulchar) { 6 | this.ulchar = ulchar; 7 | } 8 | public void use(String s) { 9 | int length = s.getBytes().length; 10 | System.out.println("\"" + s + "\""); 11 | System.out.print(" "); 12 | for (int i = 0; i < length; i++) { 13 | System.out.print(ulchar); 14 | } 15 | System.out.println(""); 16 | } 17 | public Product createClone() { 18 | Product p = null; 19 | try { 20 | p = (Product)clone(); 21 | } catch (CloneNotSupportedException e) { 22 | e.printStackTrace(); 23 | } 24 | return p; 25 | } 26 | } 27 | -------------------------------------------------------------------------------- /src/Prototype/Sample/framework/Manager.java: -------------------------------------------------------------------------------- 1 | package framework; 2 | import java.util.*; 3 | 4 | public class Manager { 5 | private HashMap showcase = new HashMap(); 6 | public void register(String name, Product proto) { 7 | showcase.put(name, proto); 8 | } 9 | public Product create(String protoname) { 10 | Product p = (Product)showcase.get(protoname); 11 | return p.createClone(); 12 | } 13 | } 14 | -------------------------------------------------------------------------------- /src/Prototype/Sample/framework/Product.java: -------------------------------------------------------------------------------- 1 | package framework; 2 | import java.lang.Cloneable; 3 | 4 | public interface Product extends Cloneable { 5 | public abstract void use(String s); 6 | public abstract Product createClone(); 7 | } 8 | -------------------------------------------------------------------------------- /src/Proxy/A1/Main.java: -------------------------------------------------------------------------------- 1 | public class Main { 2 | public static void main(String[] args) { 3 | Printable p = new PrinterProxy("Alice", "Printer"); 4 | System.out.println("现在的名字是" + p.getPrinterName() + "。"); 5 | p.setPrinterName("Bob"); 6 | System.out.println("现在的名字是" + p.getPrinterName() + "。"); 7 | p.print("Hello, world."); 8 | } 9 | } 10 | -------------------------------------------------------------------------------- /src/Proxy/A1/Printable.java: -------------------------------------------------------------------------------- 1 | public interface Printable { 2 | public abstract void setPrinterName(String name); // 设置名字 3 | public abstract String getPrinterName(); // 获取名字 4 | public abstract void print(String string); // 显示文字(打印输出) 5 | } 6 | -------------------------------------------------------------------------------- /src/Proxy/A1/Printer.java: -------------------------------------------------------------------------------- 1 | public class Printer implements Printable { 2 | private String name; 3 | public Printer() { 4 | heavyJob("正在生成Printer的实例"); 5 | } 6 | public Printer(String name) { // 构造函数 7 | this.name = name; 8 | heavyJob("正在生成Printer的实例(" + name + ")"); 9 | } 10 | public void setPrinterName(String name) { // 设置名字 11 | this.name = name; 12 | } 13 | public String getPrinterName() { // 获取名字 14 | return name; 15 | } 16 | public void print(String string) { // 显示带打印机名字的文字 17 | System.out.println("=== " + name + " ==="); 18 | System.out.println(string); 19 | } 20 | private void heavyJob(String msg) { // 重活 21 | System.out.print(msg); 22 | for (int i = 0; i < 5; i++) { 23 | try { 24 | Thread.sleep(1000); 25 | } catch (InterruptedException e) { 26 | } 27 | System.out.print("."); 28 | } 29 | System.out.println("结束。"); 30 | } 31 | } 32 | -------------------------------------------------------------------------------- /src/Proxy/Sample/Main.java: -------------------------------------------------------------------------------- 1 | public class Main { 2 | public static void main(String[] args) { 3 | Printable p = new PrinterProxy("Alice"); 4 | System.out.println("现在的名字是" + p.getPrinterName() + "。"); 5 | p.setPrinterName("Bob"); 6 | System.out.println("现在的名字是" + p.getPrinterName() + "。"); 7 | p.print("Hello, world."); 8 | } 9 | } 10 | -------------------------------------------------------------------------------- /src/Proxy/Sample/Printable.java: -------------------------------------------------------------------------------- 1 | public interface Printable { 2 | public abstract void setPrinterName(String name); // 设置名字 3 | public abstract String getPrinterName(); // 获取名字 4 | public abstract void print(String string); // 显示文字(打印输出) 5 | } 6 | -------------------------------------------------------------------------------- /src/Proxy/Sample/Printer.java: -------------------------------------------------------------------------------- 1 | public class Printer implements Printable { 2 | private String name; 3 | public Printer() { 4 | heavyJob("正在生成Printer的实例"); 5 | } 6 | public Printer(String name) { // 构造函数 7 | this.name = name; 8 | heavyJob("正在生成Printer的实例(" + name + ")"); 9 | } 10 | public void setPrinterName(String name) { // 设置名字 11 | this.name = name; 12 | } 13 | public String getPrinterName() { // 获取名字 14 | return name; 15 | } 16 | public void print(String string) { // 显示带打印机名字的文字 17 | System.out.println("=== " + name + " ==="); 18 | System.out.println(string); 19 | } 20 | private void heavyJob(String msg) { // 重活 21 | System.out.print(msg); 22 | for (int i = 0; i < 5; i++) { 23 | try { 24 | Thread.sleep(1000); 25 | } catch (InterruptedException e) { 26 | } 27 | System.out.print("."); 28 | } 29 | System.out.println("结束。"); 30 | } 31 | } 32 | -------------------------------------------------------------------------------- /src/Proxy/Sample/PrinterProxy.java: -------------------------------------------------------------------------------- 1 | public class PrinterProxy implements Printable { 2 | private String name; // 名字 3 | private Printer real; // “本人” 4 | public PrinterProxy() { 5 | } 6 | public PrinterProxy(String name) { // 构造函数 7 | this.name = name; 8 | } 9 | public synchronized void setPrinterName(String name) { // 设置名字 10 | if (real != null) { 11 | real.setPrinterName(name); // 同时设置“本人”的名字 12 | } 13 | this.name = name; 14 | } 15 | public String getPrinterName() { // 获取名字 16 | return name; 17 | } 18 | public void print(String string) { // 显示 19 | realize(); 20 | real.print(string); 21 | } 22 | private synchronized void realize() { // 生成“本人” 23 | if (real == null) { 24 | real = new Printer(name); 25 | } 26 | } 27 | } 28 | -------------------------------------------------------------------------------- /src/Singleton/A1/Main.java: -------------------------------------------------------------------------------- 1 | public class Main { 2 | public static void main(String[] args) { 3 | System.out.println("Start."); 4 | for (int i = 0; i < 10; i++) { 5 | System.out.println(i + ":" + TicketMaker.getInstance().getNextTicketNumber()); 6 | } 7 | System.out.println("End."); 8 | } 9 | } 10 | -------------------------------------------------------------------------------- /src/Singleton/A1/TicketMaker.java: -------------------------------------------------------------------------------- 1 | public class TicketMaker { 2 | private int ticket = 1000; 3 | private static TicketMaker singleton = new TicketMaker(); 4 | private TicketMaker() { 5 | } 6 | public static TicketMaker getInstance() { 7 | return singleton; 8 | } 9 | public synchronized int getNextTicketNumber() { 10 | return ticket++; 11 | } 12 | } 13 | -------------------------------------------------------------------------------- /src/Singleton/A2/Main.java: -------------------------------------------------------------------------------- 1 | public class Main { 2 | public static void main(String[] args) { 3 | System.out.println("Start."); 4 | for (int i = 0; i < 9; i++) { 5 | Triple triple = Triple.getInstance(i % 3); 6 | System.out.println(i + ":" + triple); 7 | } 8 | System.out.println("End."); 9 | } 10 | } 11 | -------------------------------------------------------------------------------- /src/Singleton/A2/Triple.java: -------------------------------------------------------------------------------- 1 | public class Triple { 2 | private static Triple[] triple = new Triple[]{ 3 | new Triple(0), 4 | new Triple(1), 5 | new Triple(2), 6 | }; 7 | private int id; 8 | private Triple(int id) { 9 | System.out.println("The instance " + id + " is created."); 10 | this.id = id; 11 | } 12 | public static Triple getInstance(int id) { 13 | return triple[id]; 14 | } 15 | public String toString() { 16 | return "[Triple id=" + id + "]"; 17 | } 18 | } 19 | -------------------------------------------------------------------------------- /src/Singleton/A3_1/Main.java: -------------------------------------------------------------------------------- 1 | public class Main extends Thread { 2 | public static void main(String[] args) { 3 | System.out.println("Start."); 4 | new Main("A").start(); 5 | new Main("B").start(); 6 | new Main("C").start(); 7 | System.out.println("End."); 8 | } 9 | public void run() { 10 | Singleton obj = Singleton.getInstance(); 11 | System.out.println(getName() + ": obj = " + obj); 12 | } 13 | public Main(String name) { 14 | super(name); 15 | } 16 | } 17 | -------------------------------------------------------------------------------- /src/Singleton/A3_1/Singleton.java: -------------------------------------------------------------------------------- 1 | public class Singleton { 2 | private static Singleton singleton = null; 3 | private Singleton() { 4 | System.out.println("生成了一个实例。"); 5 | slowdown(); 6 | } 7 | public static Singleton getInstance() { 8 | if (singleton == null) { 9 | singleton = new Singleton(); 10 | } 11 | return singleton; 12 | } 13 | private void slowdown() { 14 | try { 15 | Thread.sleep(1000); 16 | } catch (InterruptedException e) { 17 | } 18 | } 19 | } 20 | -------------------------------------------------------------------------------- /src/Singleton/A3_2/Main.java: -------------------------------------------------------------------------------- 1 | public class Main extends Thread { 2 | public static void main(String[] args) { 3 | System.out.println("Start."); 4 | new Main("A").start(); 5 | new Main("B").start(); 6 | new Main("C").start(); 7 | System.out.println("End."); 8 | } 9 | public void run() { 10 | Singleton obj = Singleton.getInstance(); 11 | System.out.println(getName() + ": obj = " + obj); 12 | } 13 | public Main(String name) { 14 | super(name); 15 | } 16 | } 17 | -------------------------------------------------------------------------------- /src/Singleton/A3_2/Singleton.java: -------------------------------------------------------------------------------- 1 | public class Singleton { 2 | private static Singleton singleton = null; 3 | private Singleton() { 4 | System.out.println("生成了一个实例。"); 5 | slowdown(); 6 | } 7 | public static synchronized Singleton getInstance() { 8 | if (singleton == null) { 9 | singleton = new Singleton(); 10 | } 11 | return singleton; 12 | } 13 | private void slowdown() { 14 | try { 15 | Thread.sleep(1000); 16 | } catch (InterruptedException e) { 17 | } 18 | } 19 | } 20 | -------------------------------------------------------------------------------- /src/Singleton/Q1/TicketMaker.java: -------------------------------------------------------------------------------- 1 | public class TicketMaker { 2 | private int ticket = 1000; 3 | public int getNextTicketNumber() { 4 | return ticket++; 5 | } 6 | } 7 | -------------------------------------------------------------------------------- /src/Singleton/Q3/Singleton.java: -------------------------------------------------------------------------------- 1 | public class Singleton { 2 | private static Singleton singleton = null; 3 | private Singleton() { 4 | System.out.println("生成了一个实例。"); 5 | } 6 | public static Singleton getInstance() { 7 | if (singleton == null) { 8 | singleton = new Singleton(); 9 | } 10 | return singleton; 11 | } 12 | } 13 | -------------------------------------------------------------------------------- /src/Singleton/Sample/Main.java: -------------------------------------------------------------------------------- 1 | public class Main { 2 | public static void main(String[] args) { 3 | System.out.println("Start."); 4 | Singleton obj1 = Singleton.getInstance(); 5 | Singleton obj2 = Singleton.getInstance(); 6 | if (obj1 == obj2) { 7 | System.out.println("obj1与obj2是相同的实例。"); 8 | } else { 9 | System.out.println("obj1与obj2是不同的实例。"); 10 | } 11 | System.out.println("End."); 12 | } 13 | } 14 | -------------------------------------------------------------------------------- /src/Singleton/Sample/Singleton.java: -------------------------------------------------------------------------------- 1 | public class Singleton { 2 | private static Singleton singleton = new Singleton(); 3 | private Singleton() { 4 | System.out.println("生成了一个实例。"); 5 | } 6 | public static Singleton getInstance() { 7 | return singleton; 8 | } 9 | } 10 | -------------------------------------------------------------------------------- /src/State/A3/Context.java: -------------------------------------------------------------------------------- 1 | public interface Context { 2 | 3 | public abstract void setClock(int hour); // 设置时间 4 | public abstract void changeState(State state); // 改变状态 5 | public abstract void callSecurityCenter(String msg); // 联系警报中心 6 | public abstract void recordLog(String msg); // 在警报中心留下记录 7 | } 8 | -------------------------------------------------------------------------------- /src/State/A3/Main.java: -------------------------------------------------------------------------------- 1 | public class Main { 2 | public static void main(String[] args) { 3 | SafeFrame frame = new SafeFrame("State Sample"); 4 | while (true) { 5 | for (int hour = 0; hour < 24; hour++) { 6 | frame.setClock(hour); // 设置时间 7 | try { 8 | Thread.sleep(1000); 9 | } catch (InterruptedException e) { 10 | } 11 | } 12 | } 13 | } 14 | } 15 | -------------------------------------------------------------------------------- /src/State/A3/NoonState.java: -------------------------------------------------------------------------------- 1 | public class NoonState implements State { 2 | private static NoonState singleton = new NoonState(); 3 | private NoonState() { // 构造函数的可见性是private 4 | } 5 | public static State getInstance() { // 获取唯一实例 6 | return singleton; 7 | } 8 | public void doClock(Context context, int hour) { // 设置时间 9 | if (hour < 9 || 17 <= hour) { 10 | context.changeState(NightState.getInstance()); 11 | } else if (9 <= hour && hour < 12 || 13 <= hour && hour < 17) { 12 | context.changeState(DayState.getInstance()); 13 | } 14 | } 15 | public void doUse(Context context) { // 使用金库 16 | context.callSecurityCenter("紧急:午餐时间使用金库!"); 17 | } 18 | public void doAlarm(Context context) { // 按下警铃 19 | context.callSecurityCenter("按下警铃(午餐时间)"); 20 | } 21 | public void doPhone(Context context) { // 正常通话 22 | context.recordLog("午餐时间的通话录音"); 23 | } 24 | public String toString() { // 显示字符串 25 | return "[午餐时间]"; 26 | } 27 | } 28 | -------------------------------------------------------------------------------- /src/State/A3/State.java: -------------------------------------------------------------------------------- 1 | public interface State { 2 | public abstract void doClock(Context context, int hour); // 设置时间 3 | public abstract void doUse(Context context); // 使用金库 4 | public abstract void doAlarm(Context context); // 按下警铃 5 | public abstract void doPhone(Context context); // 正常通话 6 | } 7 | -------------------------------------------------------------------------------- /src/State/A4/Context.java: -------------------------------------------------------------------------------- 1 | public interface Context { 2 | 3 | public abstract void setClock(int hour); // 设置时间 4 | public abstract void changeState(State state); // 改变状态 5 | public abstract void callSecurityCenter(String msg); // 联系警报中心 6 | public abstract void recordLog(String msg); // 在警报中心留下记录 7 | } 8 | -------------------------------------------------------------------------------- /src/State/A4/DayState.java: -------------------------------------------------------------------------------- 1 | public class DayState implements State { 2 | private static DayState singleton = new DayState(); 3 | private DayState() { // 构造函数的可见性是private 4 | } 5 | public static State getInstance() { // 获取唯一实例 6 | return singleton; 7 | } 8 | public void doClock(Context context, int hour) { // 设置时间 9 | if (hour < 9 || 17 <= hour) { 10 | context.changeState(NightState.getInstance()); 11 | } 12 | } 13 | public void doUse(Context context) { // 使用金库 14 | context.recordLog("使用金库(白天)"); 15 | } 16 | public void doAlarm(Context context) { // 按下警铃 17 | context.callSecurityCenter("按下警铃(白天)"); 18 | context.changeState(UrgentState.getInstance()); 19 | } 20 | public void doPhone(Context context) { // 正常通话 21 | context.callSecurityCenter("正常通话(白天)"); 22 | } 23 | public String toString() { // 显示表示类的文字 24 | return "[白天]"; 25 | } 26 | } 27 | -------------------------------------------------------------------------------- /src/State/A4/Main.java: -------------------------------------------------------------------------------- 1 | public class Main { 2 | public static void main(String[] args) { 3 | SafeFrame frame = new SafeFrame("State Sample"); 4 | while (true) { 5 | for (int hour = 0; hour < 24; hour++) { 6 | frame.setClock(hour); // 设置时间 7 | try { 8 | Thread.sleep(1000); 9 | } catch (InterruptedException e) { 10 | } 11 | } 12 | } 13 | } 14 | } 15 | -------------------------------------------------------------------------------- /src/State/A4/NightState.java: -------------------------------------------------------------------------------- 1 | public class NightState implements State { 2 | private static NightState singleton = new NightState(); 3 | private NightState() { // 构造函数的可见性是private 4 | } 5 | public static State getInstance() { // 获取唯一实例 6 | return singleton; 7 | } 8 | public void doClock(Context context, int hour) { // 设置时间 9 | if (9 <= hour && hour < 17) { 10 | context.changeState(DayState.getInstance()); 11 | } 12 | } 13 | public void doUse(Context context) { // 使用金库 14 | context.callSecurityCenter("紧急:晚上使用金库!"); 15 | } 16 | public void doAlarm(Context context) { // 按下警铃 17 | context.callSecurityCenter("按下警铃(晚上)"); 18 | context.changeState(UrgentState.getInstance()); 19 | } 20 | public void doPhone(Context context) { // 正常通话 21 | context.recordLog("晚上的通话录音"); 22 | } 23 | public String toString() { // 显示字符串 24 | return "[晚上]"; 25 | } 26 | } 27 | -------------------------------------------------------------------------------- /src/State/A4/State.java: -------------------------------------------------------------------------------- 1 | public interface State { 2 | public abstract void doClock(Context context, int hour); // 设置时间 3 | public abstract void doUse(Context context); // 使用金库 4 | public abstract void doAlarm(Context context); // 按下警铃 5 | public abstract void doPhone(Context context); // 正常通话 6 | } 7 | -------------------------------------------------------------------------------- /src/State/A4/UrgentState.java: -------------------------------------------------------------------------------- 1 | public class UrgentState implements State { 2 | private static UrgentState singleton = new UrgentState(); 3 | private UrgentState() { // 构造函数的可见性是private 4 | } 5 | public static State getInstance() { // 获取唯一实例 6 | return singleton; 7 | } 8 | public void doClock(Context context, int hour) { // 设置时间 9 | // 在设置时间处理中什么都不做 10 | } 11 | public void doUse(Context context) { // 使用金库 12 | context.callSecurityCenter("紧急:紧急时使用金库!"); 13 | } 14 | public void doAlarm(Context context) { // 按下警铃 15 | context.callSecurityCenter("按下警铃(紧急时)"); 16 | } 17 | public void doPhone(Context context) { // 正常通话 18 | context.callSecurityCenter("正常通话(紧急时)"); 19 | } 20 | public String toString() { // 显示字符串 21 | return "[紧急时]"; 22 | } 23 | } 24 | -------------------------------------------------------------------------------- /src/State/Sample/Context.java: -------------------------------------------------------------------------------- 1 | public interface Context { 2 | 3 | public abstract void setClock(int hour); // 设置时间 4 | public abstract void changeState(State state); // 改变状态 5 | public abstract void callSecurityCenter(String msg); // 联系警报中心 6 | public abstract void recordLog(String msg); // 在警报中心留下记录 7 | } 8 | -------------------------------------------------------------------------------- /src/State/Sample/DayState.java: -------------------------------------------------------------------------------- 1 | public class DayState implements State { 2 | private static DayState singleton = new DayState(); 3 | private DayState() { // 构造函数的可见性是private 4 | } 5 | public static State getInstance() { // 获取唯一实例 6 | return singleton; 7 | } 8 | public void doClock(Context context, int hour) { // 设置时间 9 | if (hour < 9 || 17 <= hour) { 10 | context.changeState(NightState.getInstance()); 11 | } 12 | } 13 | public void doUse(Context context) { // 使用金库 14 | context.recordLog("使用金库(白天)"); 15 | } 16 | public void doAlarm(Context context) { // 按下警铃 17 | context.callSecurityCenter("按下警铃(白天)"); 18 | } 19 | public void doPhone(Context context) { // 正常通话 20 | context.callSecurityCenter("正常通话(白天)"); 21 | } 22 | public String toString() { // 显示表示类的文字 23 | return "[白天]"; 24 | } 25 | } 26 | -------------------------------------------------------------------------------- /src/State/Sample/Main.java: -------------------------------------------------------------------------------- 1 | public class Main { 2 | public static void main(String[] args) { 3 | SafeFrame frame = new SafeFrame("State Sample"); 4 | while (true) { 5 | for (int hour = 0; hour < 24; hour++) { 6 | frame.setClock(hour); // 设置时间 7 | try { 8 | Thread.sleep(1000); 9 | } catch (InterruptedException e) { 10 | } 11 | } 12 | } 13 | } 14 | } 15 | -------------------------------------------------------------------------------- /src/State/Sample/NightState.java: -------------------------------------------------------------------------------- 1 | public class NightState implements State { 2 | private static NightState singleton = new NightState(); 3 | private NightState() { // 构造函数的可见性是private 4 | } 5 | public static State getInstance() { // 获取唯一实例 6 | return singleton; 7 | } 8 | public void doClock(Context context, int hour) { // 设置时间 9 | if (9 <= hour && hour < 17) { 10 | context.changeState(DayState.getInstance()); 11 | } 12 | } 13 | public void doUse(Context context) { // 使用金库 14 | context.callSecurityCenter("紧急:晚上使用金库!"); 15 | } 16 | public void doAlarm(Context context) { // 按下警铃 17 | context.callSecurityCenter("按下警铃(晚上)"); 18 | } 19 | public void doPhone(Context context) { // 正常通话 20 | context.recordLog("晚上的通话录音"); 21 | } 22 | public String toString() { // 显示表示类的文字 23 | return "[晚上]"; 24 | } 25 | } 26 | -------------------------------------------------------------------------------- /src/State/Sample/State.java: -------------------------------------------------------------------------------- 1 | public interface State { 2 | public abstract void doClock(Context context, int hour); // 设置时间 3 | public abstract void doUse(Context context); // 使用金库 4 | public abstract void doAlarm(Context context); // 按下警铃 5 | public abstract void doPhone(Context context); // 正常通话 6 | } 7 | -------------------------------------------------------------------------------- /src/Strategy/A1/Player.java: -------------------------------------------------------------------------------- 1 | public class Player { 2 | private String name; 3 | private Strategy strategy; 4 | private int wincount; 5 | private int losecount; 6 | private int gamecount; 7 | public Player(String name, Strategy strategy) { // 赋予姓名和策略 8 | this.name = name; 9 | this.strategy = strategy; 10 | } 11 | public Hand nextHand() { // 策略决定下一局要出的手势 12 | return strategy.nextHand(); 13 | } 14 | public void win() { // 胜 15 | strategy.study(true); 16 | wincount++; 17 | gamecount++; 18 | } 19 | public void lose() { // 负 20 | strategy.study(false); 21 | losecount++; 22 | gamecount++; 23 | } 24 | public void even() { // 平 25 | gamecount++; 26 | } 27 | public String toString() { 28 | return "[" + name + ":" + gamecount + " games, " + wincount + " win, " + losecount + " lose" + "]"; 29 | } 30 | } 31 | -------------------------------------------------------------------------------- /src/Strategy/A1/RandomStrategy.java: -------------------------------------------------------------------------------- 1 | import java.util.Random; 2 | 3 | public class RandomStrategy implements Strategy { 4 | private Random random; 5 | public RandomStrategy(int seed) { 6 | random = new Random(seed); 7 | } 8 | public void study(boolean win) { 9 | } 10 | public Hand nextHand() { 11 | return Hand.getHand(random.nextInt(3)); 12 | } 13 | } 14 | -------------------------------------------------------------------------------- /src/Strategy/A1/Strategy.java: -------------------------------------------------------------------------------- 1 | public interface Strategy { 2 | public abstract Hand nextHand(); 3 | public abstract void study(boolean win); 4 | } 5 | -------------------------------------------------------------------------------- /src/Strategy/A4/Main.java: -------------------------------------------------------------------------------- 1 | public class Main { 2 | public static void main(String[] args) { 3 | String[] data = { 4 | "Dumpty", "Bowman", "Carroll", "Elfland", "Alice", 5 | }; 6 | SortAndPrint sap = new SortAndPrint(data, new QuickSorter()); 7 | sap.execute(); 8 | } 9 | } 10 | -------------------------------------------------------------------------------- /src/Strategy/A4/QuickSorter.java: -------------------------------------------------------------------------------- 1 | public class QuickSorter implements Sorter { 2 | Comparable[] data; 3 | public void sort(Comparable[] data) { 4 | this.data = data; 5 | qsort(0, data.length - 1); 6 | } 7 | private void qsort(int pre, int post) { 8 | int saved_pre = pre; 9 | int saved_post = post; 10 | Comparable mid = data[(pre + post) / 2]; 11 | do { 12 | while (data[pre].compareTo(mid) < 0) { 13 | pre++; 14 | } 15 | while (mid.compareTo(data[post]) < 0) { 16 | post--; 17 | } 18 | if (pre <= post) { 19 | Comparable tmp = data[pre]; 20 | data[pre] = data[post]; 21 | data[post] = tmp; 22 | pre++; 23 | post--; 24 | } 25 | } while (pre <= post); 26 | if (saved_pre < post) { 27 | qsort(saved_pre, post); 28 | } 29 | if (pre < saved_post) { 30 | qsort(pre, saved_post); 31 | } 32 | } 33 | } 34 | -------------------------------------------------------------------------------- /src/Strategy/A4/SortAndPrint.java: -------------------------------------------------------------------------------- 1 | public class SortAndPrint { 2 | Comparable[] data; 3 | Sorter sorter; 4 | public SortAndPrint(Comparable[] data, Sorter sorter) { 5 | this.data = data; 6 | this.sorter = sorter; 7 | } 8 | public void execute() { 9 | print(); 10 | sorter.sort(data); 11 | print(); 12 | } 13 | public void print() { 14 | for (int i = 0; i < data.length; i++) { 15 | System.out.print(data[i] + ", "); 16 | } 17 | System.out.println(""); 18 | } 19 | } 20 | -------------------------------------------------------------------------------- /src/Strategy/A4/Sorter.java: -------------------------------------------------------------------------------- 1 | import java.lang.Comparable; 2 | 3 | public interface Sorter { 4 | public abstract void sort(Comparable[] data); 5 | } 6 | -------------------------------------------------------------------------------- /src/Strategy/Q4/Main.java: -------------------------------------------------------------------------------- 1 | public class Main { 2 | public static void main(String[] args) { 3 | String[] data = { 4 | "Dumpty", "Bowman", "Carroll", "Elfland", "Alice", 5 | }; 6 | SortAndPrint sap = new SortAndPrint(data, new SelectionSorter()); 7 | sap.execute(); 8 | } 9 | } 10 | -------------------------------------------------------------------------------- /src/Strategy/Q4/SelectionSorter.java: -------------------------------------------------------------------------------- 1 | public class SelectionSorter implements Sorter { 2 | public void sort(Comparable[] data) { 3 | for (int i = 0; i < data.length - 1; i++) { 4 | int min = i; 5 | for (int j = i + 1; j < data.length; j++) { 6 | if (data[min].compareTo(data[j]) > 0) { 7 | min = j; 8 | } 9 | } 10 | Comparable passingplace = data[min]; 11 | data[min] = data[i]; 12 | data[i] = passingplace; 13 | } 14 | } 15 | } 16 | -------------------------------------------------------------------------------- /src/Strategy/Q4/SortAndPrint.java: -------------------------------------------------------------------------------- 1 | public class SortAndPrint { 2 | Comparable[] data; 3 | Sorter sorter; 4 | public SortAndPrint(Comparable[] data, Sorter sorter) { 5 | this.data = data; 6 | this.sorter = sorter; 7 | } 8 | public void execute() { 9 | print(); 10 | sorter.sort(data); 11 | print(); 12 | } 13 | public void print() { 14 | for (int i = 0; i < data.length; i++) { 15 | System.out.print(data[i] + ", "); 16 | } 17 | System.out.println(""); 18 | } 19 | } 20 | -------------------------------------------------------------------------------- /src/Strategy/Q4/Sorter.java: -------------------------------------------------------------------------------- 1 | import java.lang.Comparable; 2 | 3 | public interface Sorter { 4 | public abstract void sort(Comparable[] data); 5 | } 6 | -------------------------------------------------------------------------------- /src/Strategy/Sample/Player.java: -------------------------------------------------------------------------------- 1 | public class Player { 2 | private String name; 3 | private Strategy strategy; 4 | private int wincount; 5 | private int losecount; 6 | private int gamecount; 7 | public Player(String name, Strategy strategy) { // 赋予姓名和策略 8 | this.name = name; 9 | this.strategy = strategy; 10 | } 11 | public Hand nextHand() { // 策略决定下一局要出的手势 12 | return strategy.nextHand(); 13 | } 14 | public void win() { // 胜 15 | strategy.study(true); 16 | wincount++; 17 | gamecount++; 18 | } 19 | public void lose() { // 负 20 | strategy.study(false); 21 | losecount++; 22 | gamecount++; 23 | } 24 | public void even() { // 平 25 | gamecount++; 26 | } 27 | public String toString() { 28 | return "[" + name + ":" + gamecount + " games, " + wincount + " win, " + losecount + " lose" + "]"; 29 | } 30 | } 31 | -------------------------------------------------------------------------------- /src/Strategy/Sample/Strategy.java: -------------------------------------------------------------------------------- 1 | public interface Strategy { 2 | public abstract Hand nextHand(); 3 | public abstract void study(boolean win); 4 | } 5 | -------------------------------------------------------------------------------- /src/Strategy/Sample/WinningStrategy.java: -------------------------------------------------------------------------------- 1 | import java.util.Random; 2 | 3 | public class WinningStrategy implements Strategy { 4 | private Random random; 5 | private boolean won = false; 6 | private Hand prevHand; 7 | public WinningStrategy(int seed) { 8 | random = new Random(seed); 9 | } 10 | public Hand nextHand() { 11 | if (!won) { 12 | prevHand = Hand.getHand(random.nextInt(3)); 13 | } 14 | return prevHand; 15 | } 16 | public void study(boolean win) { 17 | won = win; 18 | } 19 | } 20 | -------------------------------------------------------------------------------- /src/TemplateMethod/Sample/AbstractDisplay.java: -------------------------------------------------------------------------------- 1 | public abstract class AbstractDisplay { // 抽象类AbstractDisplay 2 | public abstract void open(); // 交给子类去实现的抽象方法(1) open 3 | public abstract void print(); // 交给子类去实现的抽象方法(2) print 4 | public abstract void close(); // 交给子类去实现的抽象方法(3) close 5 | public final void display() { // 本抽象类中实现的display方法 6 | open(); // 首先打开… 7 | for (int i = 0; i < 5; i++) { // 循环调用5次print 8 | print(); 9 | } 10 | close(); // …最后关闭。这就是display方法所实现的功能 11 | } 12 | } 13 | -------------------------------------------------------------------------------- /src/TemplateMethod/Sample/CharDisplay.java: -------------------------------------------------------------------------------- 1 | public class CharDisplay extends AbstractDisplay { // CharDisplay是AbstractDisplay的子类 2 | private char ch; // 需要显示的字符 3 | public CharDisplay(char ch) { // 构造函数中接收的字符被 4 | this.ch = ch; // 保存在字段中 5 | } 6 | public void open() { // 在父类中是抽象方法,此处重写该方法 7 | System.out.print("<<"); // 显示开始字符"<<" 8 | } 9 | public void print() { // 同样地重写print方法。该方法会在display中被重复调用 10 | System.out.print(ch); // 显示保存在字段ch中的字符 11 | } 12 | public void close() { // 同样地重写close方法 13 | System.out.println(">>"); // 显示结束字符">>" 14 | } 15 | } 16 | -------------------------------------------------------------------------------- /src/TemplateMethod/Sample/Main.java: -------------------------------------------------------------------------------- 1 | public class Main { 2 | public static void main(String[] args) { 3 | AbstractDisplay d1 = new CharDisplay('H'); // 生成一个持有'H'的CharDisplay类的实例 4 | AbstractDisplay d2 = new StringDisplay("Hello, world."); // 生成一个持有"Hello, world."的StringDisplay类的实例 5 | AbstractDisplay d3 = new StringDisplay("你好,世界。"); // 生成一个持有"你好,世界。"的StringDisplay类的实例 6 | d1.display(); // 由于d1、d2和d3都是AbstractDisplay类的子类 7 | d2.display(); // 可以调用继承的display方法 8 | d3.display(); // 实际的程序行为取决于CharDisplay类和StringDisplay类的具体实现 9 | } 10 | } 11 | -------------------------------------------------------------------------------- /src/Visitor/A1/Directory.java: -------------------------------------------------------------------------------- 1 | import java.util.Iterator; 2 | import java.util.ArrayList; 3 | 4 | public class Directory extends Entry { 5 | private String name; // 文件夹名字 6 | private ArrayList dir = new ArrayList(); // 目录条目集合 7 | public Directory(String name) { // 构造函数 8 | this.name = name; 9 | } 10 | public String getName() { // 获取名字 11 | return name; 12 | } 13 | public int getSize() { // 获取大小 14 | int size = 0; 15 | Iterator it = dir.iterator(); 16 | while (it.hasNext()) { 17 | Entry entry = (Entry)it.next(); 18 | size += entry.getSize(); 19 | } 20 | return size; 21 | } 22 | public Entry add(Entry entry) { // 增加目录条目 23 | dir.add(entry); 24 | return this; 25 | } 26 | public Iterator iterator() { // 生成Iterator 27 | return dir.iterator(); 28 | } 29 | public void accept(Visitor v) { // 接受访问者的访问 30 | v.visit(this); 31 | } 32 | } 33 | -------------------------------------------------------------------------------- /src/Visitor/A1/Element.java: -------------------------------------------------------------------------------- 1 | public interface Element { 2 | public abstract void accept(Visitor v); 3 | } 4 | -------------------------------------------------------------------------------- /src/Visitor/A1/Entry.java: -------------------------------------------------------------------------------- 1 | import java.util.Iterator; 2 | 3 | public abstract class Entry implements Element { 4 | public abstract String getName(); // 获取名字 5 | public abstract int getSize(); // 获取大小 6 | public Entry add(Entry entry) throws FileTreatmentException { // 增加目录条目 7 | throw new FileTreatmentException(); 8 | } 9 | public Iterator iterator() throws FileTreatmentException { // 生成Iterator 10 | throw new FileTreatmentException(); 11 | } 12 | public String toString() { // 显示字符串 13 | return getName() + " (" + getSize() + ")"; 14 | } 15 | } 16 | -------------------------------------------------------------------------------- /src/Visitor/A1/File.java: -------------------------------------------------------------------------------- 1 | public class File extends Entry { 2 | private String name; 3 | private int size; 4 | public File(String name, int size) { 5 | this.name = name; 6 | this.size = size; 7 | } 8 | public String getName() { 9 | return name; 10 | } 11 | public int getSize() { 12 | return size; 13 | } 14 | public void accept(Visitor v) { 15 | v.visit(this); 16 | } 17 | } 18 | -------------------------------------------------------------------------------- /src/Visitor/A1/FileFindVisitor.java: -------------------------------------------------------------------------------- 1 | import java.util.Iterator; 2 | import java.util.ArrayList; 3 | 4 | public class FileFindVisitor extends Visitor { 5 | private String filetype; 6 | private ArrayList found = new ArrayList(); 7 | public FileFindVisitor(String filetype) { // 指定.后面的文件后缀名,如".txt" 8 | this.filetype = filetype; 9 | } 10 | public Iterator getFoundFiles() { // 获取已经找到的文件 11 | return found.iterator(); 12 | } 13 | public void visit(File file) { // 在访问文件时被调用 14 | if (file.getName().endsWith(filetype)) { 15 | found.add(file); 16 | } 17 | } 18 | public void visit(Directory directory) { // 在访问文件夹时被调用 19 | Iterator it = directory.iterator(); 20 | while (it.hasNext()) { 21 | Entry entry = (Entry)it.next(); 22 | entry.accept(this); 23 | } 24 | } 25 | } 26 | -------------------------------------------------------------------------------- /src/Visitor/A1/FileTreatmentException.java: -------------------------------------------------------------------------------- 1 | public class FileTreatmentException extends RuntimeException { 2 | public FileTreatmentException() { 3 | } 4 | public FileTreatmentException(String msg) { 5 | super(msg); 6 | } 7 | } 8 | -------------------------------------------------------------------------------- /src/Visitor/A1/ListVisitor.java: -------------------------------------------------------------------------------- 1 | import java.util.Iterator; 2 | 3 | public class ListVisitor extends Visitor { 4 | private String currentdir = ""; // 当前访问的文件夹的名字 5 | public void visit(File file) { // 在访问文件时被调用 6 | System.out.println(currentdir + "/" + file); 7 | } 8 | public void visit(Directory directory) { // 在访问文件夹时被调用 9 | System.out.println(currentdir + "/" + directory); 10 | String savedir = currentdir; 11 | currentdir = currentdir + "/" + directory.getName(); 12 | Iterator it = directory.iterator(); 13 | while (it.hasNext()) { 14 | Entry entry = (Entry)it.next(); 15 | entry.accept(this); 16 | } 17 | currentdir = savedir; 18 | } 19 | } 20 | -------------------------------------------------------------------------------- /src/Visitor/A1/Visitor.java: -------------------------------------------------------------------------------- 1 | public abstract class Visitor { 2 | public abstract void visit(File file); 3 | public abstract void visit(Directory directory); 4 | } 5 | -------------------------------------------------------------------------------- /src/Visitor/A2/Directory.java: -------------------------------------------------------------------------------- 1 | import java.util.Iterator; 2 | import java.util.ArrayList; 3 | 4 | public class Directory extends Entry { 5 | private String name; // 文件夹名字 6 | private ArrayList dir = new ArrayList(); // 目录条目的集合 7 | public Directory(String name) { // 构造函数 8 | this.name = name; 9 | } 10 | public String getName() { // 获取名字 11 | return name; 12 | } 13 | public int getSize() { // 获取大小 14 | SizeVisitor v = new SizeVisitor(); 15 | accept(v); 16 | return v.getSize(); 17 | } 18 | public Entry add(Entry entry) { // 添加目录条目 19 | dir.add(entry); 20 | return this; 21 | } 22 | public Iterator iterator() { 23 | return dir.iterator(); 24 | } 25 | public void accept(Visitor v) { 26 | v.visit(this); 27 | } 28 | } 29 | -------------------------------------------------------------------------------- /src/Visitor/A2/Element.java: -------------------------------------------------------------------------------- 1 | public interface Element { 2 | public abstract void accept(Visitor v); 3 | } 4 | -------------------------------------------------------------------------------- /src/Visitor/A2/Entry.java: -------------------------------------------------------------------------------- 1 | import java.util.Iterator; 2 | 3 | public abstract class Entry implements Element { 4 | public abstract String getName(); // 获取名字 5 | public abstract int getSize(); // 获取大小 6 | public Entry add(Entry entry) throws FileTreatmentException { // 增加目录条目 7 | throw new FileTreatmentException(); 8 | } 9 | public Iterator iterator() throws FileTreatmentException { // 生成Iterator 10 | throw new FileTreatmentException(); 11 | } 12 | public String toString() { // 显示字符串 13 | return getName() + " (" + getSize() + ")"; 14 | } 15 | } 16 | -------------------------------------------------------------------------------- /src/Visitor/A2/File.java: -------------------------------------------------------------------------------- 1 | public class File extends Entry { 2 | private String name; 3 | private int size; 4 | public File(String name, int size) { 5 | this.name = name; 6 | this.size = size; 7 | } 8 | public String getName() { 9 | return name; 10 | } 11 | public int getSize() { 12 | return size; 13 | } 14 | public void accept(Visitor v) { 15 | v.visit(this); 16 | } 17 | } 18 | -------------------------------------------------------------------------------- /src/Visitor/A2/FileTreatmentException.java: -------------------------------------------------------------------------------- 1 | public class FileTreatmentException extends RuntimeException { 2 | public FileTreatmentException() { 3 | } 4 | public FileTreatmentException(String msg) { 5 | super(msg); 6 | } 7 | } 8 | -------------------------------------------------------------------------------- /src/Visitor/A2/ListVisitor.java: -------------------------------------------------------------------------------- 1 | import java.util.Iterator; 2 | 3 | public class ListVisitor extends Visitor { 4 | private String currentdir = ""; // 当前访问的文件夹的名字 5 | public void visit(File file) { // 在访问文件时被调用 6 | System.out.println(currentdir + "/" + file); 7 | } 8 | public void visit(Directory directory) { // 在访问文件夹时被调用 9 | System.out.println(currentdir + "/" + directory); 10 | String savedir = currentdir; 11 | currentdir = currentdir + "/" + directory.getName(); 12 | Iterator it = directory.iterator(); 13 | while (it.hasNext()) { 14 | Entry entry = (Entry)it.next(); 15 | entry.accept(this); 16 | } 17 | currentdir = savedir; 18 | } 19 | } 20 | -------------------------------------------------------------------------------- /src/Visitor/A2/SizeVisitor.java: -------------------------------------------------------------------------------- 1 | import java.util.Iterator; 2 | 3 | public class SizeVisitor extends Visitor { 4 | private int size = 0; 5 | public int getSize() { 6 | return size; 7 | } 8 | public void visit(File file) { 9 | size += file.getSize(); 10 | } 11 | public void visit(Directory directory) { 12 | Iterator it = directory.iterator(); 13 | while (it.hasNext()) { 14 | Entry entry = (Entry)it.next(); 15 | entry.accept(this); 16 | } 17 | } 18 | } 19 | -------------------------------------------------------------------------------- /src/Visitor/A2/Visitor.java: -------------------------------------------------------------------------------- 1 | public abstract class Visitor { 2 | public abstract void visit(File file); 3 | public abstract void visit(Directory directory); 4 | } 5 | -------------------------------------------------------------------------------- /src/Visitor/A3/Directory.java: -------------------------------------------------------------------------------- 1 | import java.util.Iterator; 2 | import java.util.ArrayList; 3 | 4 | public class Directory extends Entry { 5 | private String name; // 文件夹名字 6 | private ArrayList dir = new ArrayList(); // 目录条目集合 7 | public Directory(String name) { // 构造函数 8 | this.name = name; 9 | } 10 | public String getName() { // 获取名字 11 | return name; 12 | } 13 | public int getSize() { // 获取大小 14 | int size = 0; 15 | Iterator it = dir.iterator(); 16 | while (it.hasNext()) { 17 | Entry entry = (Entry)it.next(); 18 | size += entry.getSize(); 19 | } 20 | return size; 21 | } 22 | public Entry add(Entry entry) { // 增加目录条目 23 | dir.add(entry); 24 | return this; 25 | } 26 | public Iterator iterator() { // 生成Iterator 27 | return dir.iterator(); 28 | } 29 | public void accept(Visitor v) { // 接受访问者的访问 30 | v.visit(this); 31 | } 32 | } 33 | -------------------------------------------------------------------------------- /src/Visitor/A3/Element.java: -------------------------------------------------------------------------------- 1 | public interface Element { 2 | public abstract void accept(Visitor v); 3 | } 4 | -------------------------------------------------------------------------------- /src/Visitor/A3/ElementArrayList.java: -------------------------------------------------------------------------------- 1 | import java.util.ArrayList; 2 | import java.util.Iterator; 3 | 4 | class ElementArrayList extends ArrayList implements Element { 5 | public void accept(Visitor v) { 6 | Iterator it = iterator(); 7 | while (it.hasNext()) { 8 | Element e = (Element)it.next(); 9 | e.accept(v); 10 | } 11 | } 12 | } 13 | -------------------------------------------------------------------------------- /src/Visitor/A3/Entry.java: -------------------------------------------------------------------------------- 1 | import java.util.Iterator; 2 | 3 | public abstract class Entry implements Element { 4 | public abstract String getName(); // 获取名字 5 | public abstract int getSize(); // 获取大小 6 | public Entry add(Entry entry) throws FileTreatmentException { // 增加目录条目 7 | throw new FileTreatmentException(); 8 | } 9 | public Iterator iterator() throws FileTreatmentException { // 生成Iterator 10 | throw new FileTreatmentException(); 11 | } 12 | public String toString() { // 显示字符串 13 | return getName() + " (" + getSize() + ")"; 14 | } 15 | } 16 | -------------------------------------------------------------------------------- /src/Visitor/A3/File.java: -------------------------------------------------------------------------------- 1 | public class File extends Entry { 2 | private String name; 3 | private int size; 4 | public File(String name, int size) { 5 | this.name = name; 6 | this.size = size; 7 | } 8 | public String getName() { 9 | return name; 10 | } 11 | public int getSize() { 12 | return size; 13 | } 14 | public void accept(Visitor v) { 15 | v.visit(this); 16 | } 17 | } 18 | -------------------------------------------------------------------------------- /src/Visitor/A3/FileTreatmentException.java: -------------------------------------------------------------------------------- 1 | public class FileTreatmentException extends RuntimeException { 2 | public FileTreatmentException() { 3 | } 4 | public FileTreatmentException(String msg) { 5 | super(msg); 6 | } 7 | } 8 | -------------------------------------------------------------------------------- /src/Visitor/A3/ListVisitor.java: -------------------------------------------------------------------------------- 1 | import java.util.Iterator; 2 | 3 | public class ListVisitor extends Visitor { 4 | private String currentdir = ""; // 当前访问的文件夹的名字 5 | public void visit(File file) { // 在访问文件时被调用 6 | System.out.println(currentdir + "/" + file); 7 | } 8 | public void visit(Directory directory) { // 在访问文件夹时被调用 9 | System.out.println(currentdir + "/" + directory); 10 | String savedir = currentdir; 11 | currentdir = currentdir + "/" + directory.getName(); 12 | Iterator it = directory.iterator(); 13 | while (it.hasNext()) { 14 | Entry entry = (Entry)it.next(); 15 | entry.accept(this); 16 | } 17 | currentdir = savedir; 18 | } 19 | } 20 | -------------------------------------------------------------------------------- /src/Visitor/A3/Main.java: -------------------------------------------------------------------------------- 1 | import java.util.Iterator; 2 | 3 | public class Main { 4 | public static void main(String[] args) { 5 | try { 6 | Directory root1 = new Directory("root1"); 7 | root1.add(new File("diary.html", 10)); 8 | root1.add(new File("index.html", 20)); 9 | 10 | Directory root2 = new Directory("root2"); 11 | root2.add(new File("diary.html", 1000)); 12 | root2.add(new File("index.html", 2000)); 13 | 14 | ElementArrayList list = new ElementArrayList(); 15 | list.add(root1); 16 | list.add(root2); 17 | list.add(new File("etc.html", 1234)); 18 | 19 | list.accept(new ListVisitor()); 20 | } catch (FileTreatmentException e) { 21 | e.printStackTrace(); 22 | } 23 | } 24 | } 25 | -------------------------------------------------------------------------------- /src/Visitor/A3/Visitor.java: -------------------------------------------------------------------------------- 1 | public abstract class Visitor { 2 | public abstract void visit(File file); 3 | public abstract void visit(Directory directory); 4 | } 5 | -------------------------------------------------------------------------------- /src/Visitor/Q3/Main.java: -------------------------------------------------------------------------------- 1 | import java.util.Iterator; 2 | 3 | public class Main { 4 | public static void main(String[] args) { 5 | try { 6 | Directory root1 = new Directory("root1"); 7 | root1.add(new File("diary.html", 10)); 8 | root1.add(new File("index.html", 20)); 9 | 10 | Directory root2 = new Directory("root2"); 11 | root2.add(new File("diary.html", 1000)); 12 | root2.add(new File("index.html", 2000)); 13 | 14 | ElementArrayList list = new ElementArrayList(); 15 | list.add(root1); 16 | list.add(root2); 17 | list.add(new File("etc.html", 1234)); 18 | 19 | list.accept(new ListVisitor()); 20 | } catch (FileTreatmentException e) { 21 | e.printStackTrace(); 22 | } 23 | } 24 | } 25 | -------------------------------------------------------------------------------- /src/Visitor/Sample/Directory.java: -------------------------------------------------------------------------------- 1 | import java.util.Iterator; 2 | import java.util.ArrayList; 3 | 4 | public class Directory extends Entry { 5 | private String name; // 文件夹名字 6 | private ArrayList dir = new ArrayList(); // 目录条目集合 7 | public Directory(String name) { // 构造函数 8 | this.name = name; 9 | } 10 | public String getName() { // 获取名字 11 | return name; 12 | } 13 | public int getSize() { // 获取大小 14 | int size = 0; 15 | Iterator it = dir.iterator(); 16 | while (it.hasNext()) { 17 | Entry entry = (Entry)it.next(); 18 | size += entry.getSize(); 19 | } 20 | return size; 21 | } 22 | public Entry add(Entry entry) { // 增加目录条目 23 | dir.add(entry); 24 | return this; 25 | } 26 | public Iterator iterator() { // 生成Iterator 27 | return dir.iterator(); 28 | } 29 | public void accept(Visitor v) { // 接受访问者的访问 30 | v.visit(this); 31 | } 32 | } 33 | -------------------------------------------------------------------------------- /src/Visitor/Sample/Element.java: -------------------------------------------------------------------------------- 1 | public interface Element { 2 | public abstract void accept(Visitor v); 3 | } 4 | -------------------------------------------------------------------------------- /src/Visitor/Sample/Entry.java: -------------------------------------------------------------------------------- 1 | import java.util.Iterator; 2 | 3 | public abstract class Entry implements Element { 4 | public abstract String getName(); // 获取名字 5 | public abstract int getSize(); // 获取大小 6 | public Entry add(Entry entry) throws FileTreatmentException { // 增加目录条目 7 | throw new FileTreatmentException(); 8 | } 9 | public Iterator iterator() throws FileTreatmentException { // 生成Iterator 10 | throw new FileTreatmentException(); 11 | } 12 | public String toString() { // 显示字符串 13 | return getName() + " (" + getSize() + ")"; 14 | } 15 | } 16 | -------------------------------------------------------------------------------- /src/Visitor/Sample/File.java: -------------------------------------------------------------------------------- 1 | public class File extends Entry { 2 | private String name; 3 | private int size; 4 | public File(String name, int size) { 5 | this.name = name; 6 | this.size = size; 7 | } 8 | public String getName() { 9 | return name; 10 | } 11 | public int getSize() { 12 | return size; 13 | } 14 | public void accept(Visitor v) { 15 | v.visit(this); 16 | } 17 | } 18 | -------------------------------------------------------------------------------- /src/Visitor/Sample/FileTreatmentException.java: -------------------------------------------------------------------------------- 1 | public class FileTreatmentException extends RuntimeException { 2 | public FileTreatmentException() { 3 | } 4 | public FileTreatmentException(String msg) { 5 | super(msg); 6 | } 7 | } 8 | -------------------------------------------------------------------------------- /src/Visitor/Sample/ListVisitor.java: -------------------------------------------------------------------------------- 1 | import java.util.Iterator; 2 | 3 | public class ListVisitor extends Visitor { 4 | private String currentdir = ""; // 当前访问的文件夹的名字 5 | public void visit(File file) { // 在访问文件时被调用 6 | System.out.println(currentdir + "/" + file); 7 | } 8 | public void visit(Directory directory) { // 在访问文件夹时被调用 9 | System.out.println(currentdir + "/" + directory); 10 | String savedir = currentdir; 11 | currentdir = currentdir + "/" + directory.getName(); 12 | Iterator it = directory.iterator(); 13 | while (it.hasNext()) { 14 | Entry entry = (Entry)it.next(); 15 | entry.accept(this); 16 | } 17 | currentdir = savedir; 18 | } 19 | } 20 | -------------------------------------------------------------------------------- /src/Visitor/Sample/Visitor.java: -------------------------------------------------------------------------------- 1 | public abstract class Visitor { 2 | public abstract void visit(File file); 3 | public abstract void visit(Directory directory); 4 | } 5 | --------------------------------------------------------------------------------