├── README.md └── src ├── refactoring ├── A.java ├── RefactoringDemo2.java ├── RefactoringDemo.java ├── PairTest.java ├── Triangle.java └── TriangleTest.java ├── abstractfactory ├── DecoratorTemplate.java ├── MazeGameDemo.java ├── FactoryDemo.java └── AbstractFactory.java ├── basic ├── Hello.java ├── javainheritance │ ├── Temperature.java │ ├── VehicleErrorCode.java │ ├── ConstructorDemo.java │ ├── FruitParser.java │ ├── SuperStringTokenizer.java │ ├── CatDemo.java │ ├── Fruit.java │ ├── PolymorphismDemo.java │ ├── BicycleDemo.java │ ├── DiscountSaleDemo.java │ ├── Sale.java │ └── ComparableDemo.java ├── javaclass │ ├── PeopleDemo.java │ └── ChessApp.java └── NNMultiplication.java ├── composite ├── CompositeDemo.java ├── CompositeTemplate.java └── CompositeApp01.java ├── factorymethod ├── FactoryMethodTemplate.java └── FactoryMethodApp01.java ├── template ├── TemplateMethodTemplate.java ├── DocApp.java └── GameApp.java ├── singleton └── SingletonDemo.java ├── adaptor ├── classadaptor │ └── ClassAdaptorTemplate.java ├── objectadaptor │ └── ObjectAdaptorTemplate.java └── AdaptorApp01.java ├── etc └── ExceptionTest.java ├── strategy ├── StrategyTemplate.java └── StrategyApp01.java ├── observer ├── ObserverTemplate.java ├── noapi │ └── ObserverNoAPI.java ├── delegation │ └── ObserverDelegationDemo.java ├── stock │ └── ObserverStockDemo.java └── ObserverApp01.java ├── principle ├── MultipleInheritanceDemo.java ├── DRYDemo.java ├── LampDemo.java ├── LSP │ └── LSPDemo.java ├── OCPDemo.java └── dip │ └── ButtonPanelDemo.java ├── uml ├── Readme.md ├── BoxApp.java ├── GradeBook.java ├── GradeBookApp0.java ├── GradeBookApp1.java ├── GradeBookApp2a.java ├── GradeBookApp2.java ├── GradeBookApp3.java ├── GradeBookApp4.java ├── UniversityApp.java ├── GradeBookApp5.java ├── GradeBookApp6.java ├── GradeBookApp7.java └── GradeBookApp8.java ├── proxy └── ProxyDemo.java ├── swing └── SwingApp.java ├── decorator ├── DecoratorTemplate.java └── DecoratorApp01.java ├── bridge └── BridgeTemplate.java ├── iterator └── IterationDemo.java ├── cor └── CoRDemo.java ├── state └── StateDemo.java ├── chess ├── chessv5 │ ├── ChessBoarding.java │ └── ChessGameV5.java ├── chessv1 │ └── ChessGameV1.java ├── chessv2 │ └── ChessGameV2.java ├── chessv3 │ └── ChessGameV3.java ├── chessmvc │ └── ChessMVC.java └── chessv4 │ └── ChessGameV4.java ├── hw └── CompositeDemo.java ├── sandbox └── TestIterator.java ├── mediator ├── template │ └── MediatorTemplate.java ├── MediatorDemo.java └── BookStoreDemo.java └── mvc ├── noobserver └── NoObserverDemo.java ├── SwingDemo.java └── MVCByObserver.java /README.md: -------------------------------------------------------------------------------- 1 | # OOSE 2 | 3 | Demo code for OOSE 4 | -------------------------------------------------------------------------------- /src/refactoring/A.java: -------------------------------------------------------------------------------- 1 | package refactoring; 2 | 3 | public class A { 4 | 5 | } 6 | -------------------------------------------------------------------------------- /src/abstractfactory/DecoratorTemplate.java: -------------------------------------------------------------------------------- 1 | package abstractfactory; 2 | 3 | public class DecoratorTemplate { 4 | 5 | } 6 | -------------------------------------------------------------------------------- /src/basic/Hello.java: -------------------------------------------------------------------------------- 1 | package basic; 2 | 3 | public class Hello { 4 | 5 | public static void main(String[] args) { 6 | System.out.println("hello, John"); 7 | } 8 | 9 | } 10 | -------------------------------------------------------------------------------- /src/refactoring/RefactoringDemo2.java: -------------------------------------------------------------------------------- 1 | package refactoring; 2 | 3 | public class RefactoringDemo2 { 4 | 5 | /** 6 | * @param args 7 | */ 8 | public static void main(String[] args) { 9 | // TODO Auto-generated method stub 10 | 11 | } 12 | 13 | } 14 | -------------------------------------------------------------------------------- /src/composite/CompositeDemo.java: -------------------------------------------------------------------------------- 1 | package composite; 2 | 3 | public class CompositeDemo { 4 | 5 | /** 6 | * @param args 7 | */ 8 | public static void main(String[] args) { 9 | // TODO Auto-generated method stub 10 | System.out.println("Demo"); 11 | } 12 | 13 | } 14 | -------------------------------------------------------------------------------- /src/refactoring/RefactoringDemo.java: -------------------------------------------------------------------------------- 1 | package refactoring; 2 | 3 | public class RefactoringDemo { 4 | 5 | } 6 | 7 | //This is a simple example for demo JUnit 8 | class Pair { 9 | 10 | int a; 11 | int b; 12 | 13 | public Pair() { 14 | a =0; 15 | b=0; 16 | } 17 | public Pair(int a, int b) { 18 | this.a = a; 19 | this.b = b; 20 | } 21 | 22 | public int add() { 23 | return a+b; 24 | } 25 | } 26 | -------------------------------------------------------------------------------- /src/basic/javainheritance/Temperature.java: -------------------------------------------------------------------------------- 1 | package basic.javainheritance; 2 | 3 | // FIX this error code 4 | 5 | //Filename: Temperature.java 6 | PUBLIC CLASS temperature { 7 | PUBLIC static void main(string args) { 8 | double fahrenheit = 62.5; 9 | double celsius = f2c(fahrenheit); 10 | System.out.println(fahrenheit + 'F' + 11 | " = " + Celsius + 'C'); 12 | } 13 | double f2c(float fahr) { 14 | RETURN (fahr - 32) * 5 / 9; 15 | } 16 | } 17 | } 18 | -------------------------------------------------------------------------------- /src/basic/javainheritance/VehicleErrorCode.java: -------------------------------------------------------------------------------- 1 | package basic.javainheritance; 2 | 3 | public class VehicleErrorCode { 4 | 5 | } 6 | 7 | class Vehicle { 8 | int speed; 9 | 10 | public Vehicle(int speed) { 11 | this.speed = speed; 12 | } 13 | } 14 | 15 | class Bike extends Vehicle { 16 | int seatHeight; 17 | 18 | public Bike(int seatHeight) { 19 | super(); 20 | this.seatHeight = seatHeight; 21 | } 22 | 23 | void setHeight(int) { 24 | this.seatHeight = seatHeight; 25 | } 26 | } 27 | -------------------------------------------------------------------------------- /src/basic/javainheritance/ConstructorDemo.java: -------------------------------------------------------------------------------- 1 | package basic.javainheritance; 2 | 3 | public class ConstructorDemo { 4 | public static void main(String[] args) { 5 | 6 | } 7 | } 8 | 9 | class SuperClass { 10 | 11 | } 12 | 13 | class SubClass extends SuperClass { 14 | 15 | } 16 | 17 | class SuperClass2 { 18 | public SuperClass2(int x) { 19 | 20 | } 21 | } 22 | 23 | // This will have compile error because its superclass has no default 24 | // constructor 25 | class SubClass2 extends SuperClass2 { 26 | public SubClass2(int x) { 27 | super(x); 28 | } 29 | } -------------------------------------------------------------------------------- /src/factorymethod/FactoryMethodTemplate.java: -------------------------------------------------------------------------------- 1 | package factorymethod; 2 | 3 | abstract class Creator { 4 | Product p; 5 | 6 | public void doSomething() { 7 | p = factoryMethod(); 8 | // ... 9 | } 10 | 11 | public abstract Product factoryMethod(); 12 | } 13 | 14 | class ConcreteCreator extends Creator { 15 | public Product factoryMethod() { 16 | return new ConcreteProduct(); 17 | } 18 | } 19 | 20 | abstract class Product { 21 | abstract void operation(); 22 | } 23 | 24 | class ConcreteProduct extends Product { 25 | void operation() { 26 | // ... 27 | } 28 | } -------------------------------------------------------------------------------- /src/template/TemplateMethodTemplate.java: -------------------------------------------------------------------------------- 1 | package template; 2 | 3 | abstract class AbstractClass { 4 | final void templateMethod() { 5 | System.out.println("Template method"); 6 | primitiveOp1(); 7 | primitiveOp2(); 8 | } 9 | abstract void primitiveOp1(); 10 | abstract void primitiveOp2(); 11 | } 12 | 13 | class ConcreteClass extends AbstractClass { 14 | void primitiveOp1() { 15 | System.out.println("Primitive operation 1"); 16 | } 17 | void primitiveOp2() { 18 | System.out.println("Primitive operation 2"); 19 | } 20 | } 21 | 22 | public class TemplateMethodTemplate { 23 | 24 | } 25 | -------------------------------------------------------------------------------- /src/template/DocApp.java: -------------------------------------------------------------------------------- 1 | package template; 2 | 3 | class DocApp { 4 | // TEMPLATE METHOD 5 | final void openDocument(String name) { 6 | if (!canOpenDocument(name)) { 7 | // cannot handle this document return; 8 | } 9 | Document doc = doCreateDocument(); 10 | if (doc) { 11 | doc.addDocument(doc); 12 | aboutToOpenDocument(doc); 13 | doc.open(); 14 | doc.doRead(); 15 | } 16 | } 17 | 18 | abstract boolean canOpenDocument(String); // PRIMITIVE METHOD 19 | 20 | abstract aboutToOpenDocument(Document); // PRIMITIVE METHOD 21 | 22 | abstract Document doCreateDocument(); // PRIMITIVE METHOD 23 | } 24 | -------------------------------------------------------------------------------- /src/refactoring/PairTest.java: -------------------------------------------------------------------------------- 1 | package refactoring; 2 | 3 | import static org.junit.Assert.*; 4 | import junit.framework.Assert; 5 | 6 | import org.junit.After; 7 | import org.junit.Before; 8 | import org.junit.Test; 9 | 10 | public class PairTest extends Pair { 11 | 12 | @Before 13 | public void setUp() throws Exception { 14 | } 15 | 16 | @After 17 | public void tearDown() throws Exception { 18 | } 19 | 20 | @Test 21 | public void test() { 22 | //fail("Not yet implemented"); 23 | 24 | Pair p = new Pair(10, 12); 25 | //Assert.assertEquals(20, p.add()); 26 | Assert.assertEquals(22, p.add()); 27 | } 28 | 29 | } 30 | -------------------------------------------------------------------------------- /src/singleton/SingletonDemo.java: -------------------------------------------------------------------------------- 1 | package singleton; 2 | 3 | public class SingletonDemo { 4 | public static void main(String[] args) { 5 | 6 | Radio r = Radio.instance(); 7 | System.out.println(r); 8 | r = null; 9 | r = Radio.instance(); 10 | System.out.println(r); 11 | } 12 | 13 | } 14 | 15 | class Radio { 16 | private static Radio uniqueInstance; 17 | 18 | String station; 19 | 20 | public static Radio instance() { 21 | if (uniqueInstance == null) { 22 | uniqueInstance = new Radio(); 23 | } 24 | return uniqueInstance; 25 | } 26 | 27 | private Radio() { 28 | station = "default station"; 29 | } 30 | 31 | } 32 | -------------------------------------------------------------------------------- /src/adaptor/classadaptor/ClassAdaptorTemplate.java: -------------------------------------------------------------------------------- 1 | package adaptor.classadaptor; 2 | // Adaptee的specificRequest()對應到Target的request() 3 | interface Target { 4 | public void request(Object arg); 5 | } 6 | 7 | class Adaptee { 8 | public void SpecificRequest(Object arg) { 9 | //... 10 | } 11 | } 12 | 13 | class Adapter extends Adaptee implements Target { 14 | public void request(Object arg) { 15 | this.SpecificRequest(arg); 16 | } 17 | 18 | } 19 | 20 | class Client { 21 | // t 可以是一個Target, 或是一個Adapter (實作了Target) 22 | public void makeRequest(Target t, Object o) { 23 | t.request(o); 24 | } 25 | } -------------------------------------------------------------------------------- /src/basic/javainheritance/FruitParser.java: -------------------------------------------------------------------------------- 1 | package basic.javainheritance; 2 | 3 | import java.util.StringTokenizer; 4 | 5 | public class FruitParser extends StringTokenizer { 6 | String[] fruit_set = { "apple", "avocado", "banana", "cherry", "coconut", "jujube", "durian", "grape", "grapefruit", 7 | "guava", "lemon", "lichee", "orange", "kiwi" }; 8 | 9 | public String[] getFruits() { 10 | String [] r = {}; 11 | return r; 12 | } 13 | 14 | public static void main(String[] args) { 15 | String s = "I like apple, banana, and orange. Marry like kiwi"; 16 | FruitParser f = new FruitParser(s); 17 | String[] fruits = f.getFruits(); 18 | } 19 | } 20 | -------------------------------------------------------------------------------- /src/etc/ExceptionTest.java: -------------------------------------------------------------------------------- 1 | package etc; 2 | 3 | import java.util.Scanner; 4 | 5 | public class ExceptionTest { 6 | 7 | public static void main(String[] args) throws Exception { 8 | ExceptionTest t = new ExceptionTest(); 9 | t.m1(); 10 | 11 | } 12 | 13 | public void m1() throws Exception{ 14 | int x = 0; 15 | Scanner sc = new Scanner(System.in); 16 | try { 17 | if (x >= 0) 18 | throw new Exception(); 19 | x++; 20 | } catch (Exception e) { 21 | throw new Exception(); 22 | //return; 23 | // System.exit(0); 24 | } finally { 25 | System.out.println("finally"); 26 | } 27 | System.out.println("after"); 28 | 29 | } 30 | 31 | } 32 | -------------------------------------------------------------------------------- /src/adaptor/objectadaptor/ObjectAdaptorTemplate.java: -------------------------------------------------------------------------------- 1 | package adaptor.objectadaptor; 2 | 3 | // Adaptee的specificRequest()對應到Target的request() 4 | class Target { 5 | public void request(Object arg) { 6 | // ... 7 | } 8 | } 9 | 10 | class Adapter extends Target { 11 | Adaptee adaptee; 12 | 13 | public Adapter(Adaptee a) { 14 | this.adaptee = a; 15 | } 16 | 17 | public void request(Object arg) { 18 | adaptee.specificRequest(arg); 19 | } 20 | } 21 | 22 | class Adaptee { 23 | public void specificRequest(Object arg) { 24 | // ... 25 | } 26 | 27 | } 28 | 29 | class Client { 30 | public void main(String args[]) { 31 | Target t = new Adapter(new Adaptee()); 32 | t.request(new Integer(1)); 33 | } 34 | } 35 | -------------------------------------------------------------------------------- /src/strategy/StrategyTemplate.java: -------------------------------------------------------------------------------- 1 | package strategy; 2 | 3 | class Context { 4 | Strategy s; 5 | 6 | public Context(Strategy s) { 7 | this.s = s; 8 | } 9 | public void doIt() { 10 | System.out.println("Doing something"); 11 | s.execute(); 12 | } 13 | } 14 | 15 | class Strategy1 implements Strategy { 16 | public void execute() { 17 | System.out.println("Using strategy 1"); 18 | } 19 | } 20 | 21 | class Strategy2 implements Strategy { 22 | public void execute() { 23 | System.out.println("Using strategy 2"); 24 | } 25 | } 26 | 27 | interface Strategy{ 28 | public void execute(); 29 | } 30 | 31 | public class StrategyTemplate { 32 | 33 | public static void main(String[] args) { 34 | Strategy s1 = new Strategy1(); 35 | Context context = new Context(s1); 36 | context.doIt(); 37 | } 38 | } 39 | -------------------------------------------------------------------------------- /src/refactoring/Triangle.java: -------------------------------------------------------------------------------- 1 | package refactoring; 2 | 3 | // 4 | public class Triangle { 5 | int a, b, c; 6 | 7 | public Triangle(int a, int b, int c) { 8 | this.a = a; 9 | this.b = b; 10 | this.c = c; 11 | } 12 | 13 | public String getType() { 14 | String result = ""; 15 | 16 | if ((a + b < c) || (a + c < b) || (c + b < a)) { 17 | result = "���O�T����"; 18 | return result; 19 | } 20 | else 21 | result = "�@��T����"; 22 | 23 | if (a == b && b == c ) { 24 | result = "���T����"; 25 | return result; 26 | } 27 | 28 | if ((a == b) || (b == c) || (a == c)) { 29 | result = "���y�T����"; 30 | return result; 31 | } 32 | 33 | if ((a * a + b * b == c * c) || (b * b + c * c == a * a) 34 | || (a * a + c * c == b * b)) { 35 | result = "�����T����"; 36 | return result; 37 | } 38 | 39 | return result; 40 | } 41 | 42 | } 43 | -------------------------------------------------------------------------------- /src/observer/ObserverTemplate.java: -------------------------------------------------------------------------------- 1 | package observer; 2 | 3 | import java.util.Observable; 4 | 5 | public class ObserverTemplate { 6 | 7 | public static void main(String[] args) { 8 | Subject s = new Subject(); 9 | 10 | View1 v1 = new View1(); 11 | View2 v2 = new View2(); 12 | s.addObserver(v1); 13 | s.addObserver(v2); 14 | } 15 | 16 | } 17 | 18 | class Subject extends java.util.Observable { 19 | int data; 20 | 21 | public Subject() { 22 | data = 0; 23 | } 24 | 25 | public void setData(int newValue) { 26 | data = newValue; 27 | this.setChanged(); 28 | this.notifyObservers(); 29 | } 30 | 31 | } 32 | 33 | class View1 implements java.util.Observer { 34 | public void update(Observable arg0, Object arg1) { 35 | // update the view 36 | } 37 | } 38 | 39 | class View2 implements java.util.Observer { 40 | public void update(Observable o, Object arg) { 41 | // update the view 42 | } 43 | } -------------------------------------------------------------------------------- /src/principle/MultipleInheritanceDemo.java: -------------------------------------------------------------------------------- 1 | /** 2 | * To demo how to use delegation to implement "multiple inheritance" 3 | */ 4 | 5 | package principle; 6 | 7 | public class MultipleInheritanceDemo { 8 | 9 | public static void main(String[] args) { 10 | WaterMoto waterMoto = new WaterMoto(new Boat()); 11 | 12 | waterMoto.drive(); 13 | waterMoto.driveOverWater(); 14 | 15 | } 16 | 17 | } 18 | 19 | class Boat { 20 | public void driveOverWater() { 21 | System.out.println("drive over water"); 22 | } 23 | } 24 | 25 | class Moto { 26 | public void drive() { 27 | System.out.println("drive"); 28 | } 29 | } 30 | 31 | class WaterMoto extends Moto { 32 | Boat boat; 33 | 34 | public WaterMoto(Boat b) { 35 | this.boat = b; 36 | } 37 | 38 | /* 39 | * delegate the driveOverWater to another "boat" object 40 | */ 41 | public void driveOverWater() { 42 | boat.driveOverWater(); 43 | } 44 | } 45 | -------------------------------------------------------------------------------- /src/basic/javainheritance/SuperStringTokenizer.java: -------------------------------------------------------------------------------- 1 | package basic.javainheritance; 2 | import java.util.*; 3 | 4 | public class SuperStringTokenizer extends StringTokenizer { 5 | 6 | public SuperStringTokenizer(String arg0) { 7 | super(arg0); 8 | 9 | // StringTokenizer st = new StringTokenizer("this is a book"); 10 | // 11 | // while (st.hasMoreElements()) { 12 | // String s = st.nextToken(); 13 | // System.out.println(s); 14 | // } 15 | } 16 | 17 | /** 18 | * @param args 19 | */ 20 | public static void main(String[] args) { 21 | // TODO Auto-generated method stub 22 | SuperStringTokenizer st = new SuperStringTokenizer("this is a book"); 23 | while (st.hasMoreElements()) { 24 | String s = st.nextToken(); 25 | System.out.println(s); 26 | } 27 | } 28 | 29 | public String nextToken() { 30 | String a = super.nextToken(); 31 | return new String(a.toUpperCase()); 32 | //return null; 33 | 34 | } 35 | } 36 | -------------------------------------------------------------------------------- /src/uml/Readme.md: -------------------------------------------------------------------------------- 1 | Readme of GRadeBookApp example 2 | 3 | App0 4 | * initial implementation of Course management system 5 | * student, teacher, course 6 | * how to define a class 7 | 8 | App1 9 | * offer relation 10 | * understand 1-to-many relationship, how to map to java code 11 | 12 | App2, 2a 13 | * take course 14 | * understand many-to-many relationship 15 | 16 | App3 17 | * score(Course, Student, int grade) 18 | * understand "use" relationship 19 | 20 | App4 21 | * define a "Member" class 22 | * understand "Generalization" relationship 23 | 24 | ==== 25 | 26 | App5 27 | * Interface implementation 28 | * instructor interface, two implementors 29 | 30 | App6 31 | * Refactoring: Too long method & magic number 32 | * split main() method 33 | * define an interface to save constant variable 34 | 35 | App7 36 | * Strategy design pattern 37 | * Course.showSortedGrade() 38 | 39 | App8 40 | * Refactoring: Grade class 41 | * exception handling 42 | -------------------------------------------------------------------------------- /src/basic/javainheritance/CatDemo.java: -------------------------------------------------------------------------------- 1 | package basic.javainheritance; 2 | 3 | class Cat extends Animal { 4 | public static void testClassMethod() { 5 | System.out.println("The class method" + " in Cat."); 6 | } 7 | public void testInstanceMethod() { 8 | System.out.println("The instance method" + " in Cat."); 9 | } 10 | 11 | public static void main(String[] args) { 12 | Cat myCat = new Cat(); 13 | Animal myAnimal = myCat; 14 | Animal.testClassMethod(); 15 | myAnimal.testInstanceMethod(); 16 | 17 | Cat.testClassMethod(); 18 | } 19 | } 20 | 21 | class Animal { 22 | public static void testClassMethod() { 23 | System.out.println("The class" + " method in Animal."); 24 | } 25 | public void testInstanceMethod() { 26 | System.out.println("The instance " + " method in Animal."); 27 | } 28 | } 29 | 30 | public class CatDemo { 31 | 32 | } 33 | -------------------------------------------------------------------------------- /src/principle/DRYDemo.java: -------------------------------------------------------------------------------- 1 | /** 2 | * This program is to demo the design principle "Don¡¦t repeat yourself (DRY)" 3 | * 4 | */ 5 | 6 | package principle; 7 | 8 | 9 | class DRYDemo { 10 | public static void main(String[] arg) { 11 | People p1 = new People("john", 1.7, 75); 12 | System.out.println(p1.toString()); 13 | } 14 | } 15 | 16 | class People { 17 | 18 | String name; 19 | double height; 20 | int weight; 21 | double BMI; // when you change the height or weight. 22 | 23 | public People(String name, double h, int w) { 24 | this.name = name; 25 | this.height = h; 26 | this.weight = w; 27 | setBMI(); 28 | } 29 | 30 | public void setHeight(double h) { 31 | this.height = h; 32 | setBMI(); 33 | } 34 | 35 | public void setWeight(int w) { 36 | this.weight = w; 37 | setBMI(); 38 | } 39 | 40 | /* 41 | * move the setting of BMI as a method, thus reduce the repeat of the 42 | */ 43 | private void setBMI() { 44 | BMI = (double) weight / (height * height); 45 | } 46 | 47 | } 48 | -------------------------------------------------------------------------------- /src/proxy/ProxyDemo.java: -------------------------------------------------------------------------------- 1 | package proxy; 2 | 3 | public class ProxyDemo { 4 | 5 | /** 6 | * @param args 7 | */ 8 | public static void main(String[] args) { 9 | Country c = new Country("Taiwan"); 10 | Ambassador a = new Ambassador(c); 11 | a.requestHelp(false); 12 | 13 | a.requestHelp(true); 14 | } 15 | 16 | } 17 | 18 | 19 | interface handleHelp { 20 | public void requestHelp(boolean isComplexity); 21 | } 22 | 23 | class Country implements handleHelp { 24 | String name; 25 | public Country(String name) { 26 | this.name = name; 27 | } 28 | public void requestHelp(boolean isComplexity) { 29 | System.out.println("I am "+ name + ", I will help you"); 30 | } 31 | } 32 | 33 | class Ambassador implements handleHelp { 34 | Country c; 35 | 36 | public Ambassador(Country c) { 37 | this.c = c; 38 | } 39 | 40 | public void requestHelp(boolean isComplexity) { 41 | System.out.println("I ambassador Hsueh, I am help you..."); 42 | if (isComplexity) { 43 | c.requestHelp(true); 44 | } 45 | else { 46 | System.out.println("Done!"); 47 | } 48 | } 49 | } 50 | -------------------------------------------------------------------------------- /src/strategy/StrategyApp01.java: -------------------------------------------------------------------------------- 1 | class Data { 2 | int[] data = {100,92,43,87,23}; 3 | Sorter s; 4 | 5 | public Data(Sorter s) { 6 | this.s = s; 7 | } 8 | public void setSorter(Sorter s) { 9 | this.s = s; 10 | } 11 | public void sort() { 12 | System.out.println("Sorting..."); 13 | s.sort(data); 14 | } 15 | public void show() { 16 | for (int d: data) 17 | System.out.println(d); 18 | } 19 | } 20 | 21 | class SelectionSorter implements Sorter { 22 | public void sort(int[] d) { 23 | System.out.println("selection sort done"); 24 | } 25 | } 26 | 27 | class BubbleSorter implements Sorter { 28 | public void sort(int[] d) { 29 | System.out.println("BubbleSorter sort done"); 30 | } 31 | } 32 | 33 | interface Sorter{ 34 | public void sort(int[] d); 35 | } 36 | 37 | 38 | 39 | public class StrategyApp01 { 40 | 41 | public static void main(String[] args) { 42 | 43 | Sorter s1 = new SelectionSorter(); 44 | Data data = new Data(s1); 45 | data.sort(); 46 | data.show(); 47 | 48 | Sorter s2 = new BubbleSorter(); 49 | data.setSorter(s2); 50 | data.sort(); 51 | data.show(); 52 | } 53 | } 54 | -------------------------------------------------------------------------------- /src/swing/SwingApp.java: -------------------------------------------------------------------------------- 1 | import java.awt.TextField; 2 | import java.awt.event.ActionEvent; 3 | import java.awt.event.ActionListener; 4 | import javax.swing.JButton; 5 | import javax.swing.JFrame; 6 | import java.awt.FlowLayout; 7 | 8 | public class SwingApp { 9 | public static void main(String[] args) { 10 | MainPanel p = new MainPanel(); 11 | 12 | p.setVisible(true); 13 | } 14 | } 15 | 16 | class MainPanel extends JFrame implements ActionListener { 17 | static int id = 0; //just for setting location 18 | private JButton inc = new JButton("INC"); 19 | private JButton dec = new JButton("DEC"); 20 | 21 | public MainPanel() { 22 | inc.addActionListener(this); 23 | dec.addActionListener(this); 24 | 25 | getContentPane().setLayout(new FlowLayout()); 26 | add(inc); 27 | add(dec); 28 | this.setTitle("demo"); 29 | this.setSize(200, 100); 30 | this.setDefaultCloseOperation(EXIT_ON_CLOSE); 31 | } 32 | 33 | public void actionPerformed(ActionEvent arg0) { 34 | if (arg0.getActionCommand() == "INC") { 35 | System.out.println("INC"); 36 | } 37 | else { 38 | System.out.println("DEC"); 39 | } 40 | } 41 | } 42 | 43 | -------------------------------------------------------------------------------- /src/basic/javainheritance/Fruit.java: -------------------------------------------------------------------------------- 1 | package basic.javainheritance; 2 | 3 | interface Comparable { 4 | public boolean betterThan(Comparable x); 5 | } 6 | 7 | class Util { 8 | public static Object best(Comparable x, Comparable y, Comparable z) { 9 | if (x.betterThan(y)) { 10 | if (x.betterThan(z)) 11 | return x; 12 | else 13 | return z; 14 | } else if (y.betterThan(z)) { 15 | return y; 16 | } else 17 | return z; 18 | } 19 | } 20 | 21 | class Fruit implements Comparable { 22 | String name; 23 | int price; 24 | int sweetDegree; 25 | int waterDegree; 26 | 27 | public static void main(String args[]) { 28 | Fruit f1 = new Fruit(12), f2 = new Fruit(23), f3 = new Fruit(9); 29 | Fruit best = (Fruit) Util.best(f1, f2, f3); 30 | // best 為何? 31 | } 32 | 33 | public boolean betterThan(Comparable x) { 34 | if (x instanceof Fruit) 35 | if (this.sweetDegree > ((Fruit) x).sweetDegree) 36 | return true; 37 | else 38 | return false; 39 | else { 40 | System.out.println("錯誤的比較"); 41 | return false; 42 | } 43 | } 44 | 45 | public Fruit(int sweetDegree) { 46 | this.sweetDegree = sweetDegree; 47 | } 48 | } 49 | -------------------------------------------------------------------------------- /src/uml/BoxApp.java: -------------------------------------------------------------------------------- 1 | package uml; 2 | 3 | public class BoxApp { 4 | 5 | public static void main(String[] args) { 6 | Shape[] box = { new Rectangle(4, 5), new Triangle(20, 4), new Circle(10) }; 7 | double a = new BoxApp().totalArea(box); 8 | System.out.println(a); 9 | } 10 | 11 | public double totalArea(Shape[] box) { 12 | double area = 0; 13 | for (Shape s : box) { 14 | area += s.getArea(); 15 | } 16 | return area; 17 | } 18 | } 19 | 20 | interface Shape { 21 | public double getArea(); 22 | } 23 | 24 | class Rectangle implements Shape { 25 | 26 | double h, w; 27 | 28 | public Rectangle(int h, int w) { 29 | this.h = h; 30 | this.w = w; 31 | } 32 | 33 | @Override 34 | public double getArea() { 35 | return h * w; 36 | } 37 | } 38 | 39 | class Triangle implements Shape { 40 | double base, h; 41 | 42 | public Triangle(int base, int h) { 43 | this.base = base; 44 | this.h = h; 45 | } 46 | 47 | @Override 48 | public double getArea() { 49 | return (base * h) / 2; 50 | } 51 | } 52 | 53 | class Circle implements Shape { 54 | double r; 55 | 56 | public Circle(double r) { 57 | this.r = r; 58 | } 59 | 60 | @Override 61 | public double getArea() { 62 | return (r / 2) * (r / 2) * 3.14; 63 | } 64 | } 65 | -------------------------------------------------------------------------------- /src/uml/GradeBook.java: -------------------------------------------------------------------------------- 1 | package uml; 2 | 3 | public class GradeBook { 4 | 5 | // how can we keep the grades private? 6 | int grades[][]; 7 | int subjectAvg[]; 8 | int studentAvg[]; 9 | 10 | public GradeBook(int[][] grades) { 11 | 12 | } 13 | 14 | public String getSubjectAvg(int jid) { 15 | // TODO Auto-generated method stub 16 | return null; 17 | } 18 | 19 | public String getStudentAvg(int sid) { 20 | // TODO Auto-generated method stub 21 | return null; 22 | } 23 | 24 | private double[] getSubjectAvg() { 25 | // TODO Auto-generated method stub 26 | return null; 27 | } 28 | 29 | private double[] getStudentAvg() { 30 | // TODO Auto-generated method stub 31 | return null; 32 | } 33 | 34 | public static void main(String[] args) { 35 | int[][] grades = { { 12, 23, 34 }, { 34, 45, 56 }, { 67, 78, 90 }, { 1, 1, 1 } }; 36 | GradeBook g = new GradeBook(grades); 37 | 38 | int sid = 1; 39 | System.out.println("The average for student " + sid + " is " + g.getStudentAvg(sid)); 40 | 41 | int jid = 0; // subject ID 42 | System.out.println("The average for subject " + jid + " is " + g.getSubjectAvg(jid)); 43 | 44 | double[] subjectAvg = g.getStudentAvg(); 45 | double[] studentAvg = g.getSubjectAvg(); 46 | 47 | } 48 | 49 | } 50 | -------------------------------------------------------------------------------- /src/decorator/DecoratorTemplate.java: -------------------------------------------------------------------------------- 1 | package decorator; 2 | 3 | abstract class Component { 4 | abstract void op(); 5 | } 6 | 7 | class ConcreteComponent extends Component { 8 | void op() { 9 | System.out.println("Basic behavior"); 10 | } 11 | } 12 | 13 | abstract class Decorator extends Component { 14 | Component c; 15 | 16 | public Decorator(Component c) { 17 | this.c = c; 18 | } 19 | 20 | void op() { 21 | c.op(); 22 | } 23 | } 24 | 25 | class ConcreteDecorator1 extends Decorator { 26 | public ConcreteDecorator1(Component c) { 27 | super(c); 28 | } 29 | 30 | void op() { 31 | super.op(); 32 | addedBehavior(); 33 | } 34 | 35 | void addedBehavior() { 36 | System.out.println("Added behavior 1"); 37 | } 38 | } 39 | 40 | class ConcreteDecorator2 extends Decorator { 41 | public ConcreteDecorator2(Component c) { 42 | super(c); 43 | } 44 | 45 | void op() { 46 | super.op(); 47 | addedBehavior(); 48 | } 49 | 50 | void addedBehavior() { 51 | System.out.println("Added behavior 2"); 52 | } 53 | } 54 | 55 | public class DecoratorTemplate { 56 | public static void main(String[] args) { 57 | Component cc = new ConcreteComponent(); 58 | cc.op(); 59 | Component c1 = new ConcreteDecorator1(new ConcreteDecorator2(cc)); 60 | c1.op(); 61 | } 62 | } 63 | -------------------------------------------------------------------------------- /src/decorator/DecoratorApp01.java: -------------------------------------------------------------------------------- 1 | abstract class AbstractTree { 2 | abstract void sing(); 3 | } 4 | 5 | class Tree extends AbstractTree { 6 | void sing() { 7 | System.out.println("I am a Chrismax."); 8 | } 9 | } 10 | 11 | abstract class TreeDecorator extends AbstractTree { 12 | // YOUR CODE HERE 13 | 14 | } 15 | 16 | class Bell extends TreeDecorator { 17 | public Bell(AbstractTree c) { 18 | super(c); 19 | } 20 | 21 | void sing() { 22 | System.out.print("I have a Bell, "); 23 | // ONE LINE CODE 24 | } 25 | } 26 | 27 | class Candy extends TreeDecorator { 28 | public Candy(AbstractTree c) { 29 | super(c); 30 | } 31 | 32 | void sing() { 33 | System.out.print("I have a Candy, "); 34 | super.sing(); 35 | } 36 | } 37 | 38 | class Gift extends TreeDecorator { 39 | public Gift(AbstractTree c) { 40 | super(c); 41 | } 42 | 43 | void sing() { 44 | // YOUR CODE HERE 45 | } 46 | } 47 | 48 | public class DecoratorApp02 { 49 | 50 | public static void main(String[] args) { 51 | // a simple tree 52 | AbstractTree t1 = new Tree(); 53 | t1.sing(); 54 | 55 | AbstractTree t2 = new Bell(t1); 56 | t2.sing(); 57 | 58 | /* 59 | If I want to show 60 | I have a Bell, I have a Gift, I have a Candy, I am a Chrismax. 61 | */ 62 | // YOUR CODE HERE 63 | } 64 | 65 | } -------------------------------------------------------------------------------- /src/bridge/BridgeTemplate.java: -------------------------------------------------------------------------------- 1 | package bridge; 2 | 3 | interface Implementor { 4 | public void m1(); 5 | public void m2(); 6 | } 7 | 8 | class ConcreteImplA implements Implementor { 9 | public void m1() { 10 | // ... 11 | } 12 | 13 | public void m2() { 14 | // ... 15 | } 16 | } 17 | 18 | class ConcreteImplB implements Implementor { 19 | public void m1() { 20 | // ... 21 | } 22 | 23 | public void m2() { 24 | // ... 25 | } 26 | } 27 | 28 | abstract class Abstraction { 29 | Implementor imp; 30 | 31 | public Abstraction(Implementor imp) { 32 | this.imp = imp; 33 | } 34 | 35 | protected void m1() { 36 | imp.m1(); 37 | } 38 | 39 | protected void m2() { 40 | imp.m2(); 41 | } 42 | 43 | abstract void operation(); 44 | } 45 | 46 | class RefinedAbstraction1 extends Abstraction { 47 | public RefinedAbstraction1(Implementor imp) { 48 | super(imp); 49 | } 50 | 51 | // 每個 RefinedAbstraction 執行 operation 的方式可能不同。先 m1() 再 m2() 52 | void operation() { 53 | m1(); 54 | m2(); 55 | // ... 56 | } 57 | } 58 | 59 | class RefinedAbstraction2 extends Abstraction { 60 | public RefinedAbstraction2(Implementor imp) { 61 | super(imp); 62 | } 63 | 64 | // 每個 RefinedAbstraction 執行 operation 的方式可能不同。先 m2() 再 m1() 65 | void operation() { 66 | m2(); 67 | m1(); 68 | // ... 69 | } 70 | } -------------------------------------------------------------------------------- /src/template/GameApp.java: -------------------------------------------------------------------------------- 1 | package template; 2 | 3 | abstract class Game { 4 | protected int playersCount; 5 | 6 | // TEMPLATE METHOD 7 | final void playOneGame(int playersCount) { 8 | this.playersCount = playersCount; 9 | initializeGame(); 10 | int j = 0; 11 | while (!endOfGame()) { 12 | makePlay(j); 13 | j = (j + 1) % playersCount; 14 | } 15 | printWinner(); 16 | } 17 | 18 | abstract void initializeGame(); // PRIMITIVE METHOD 19 | 20 | abstract void makePlay(int player); // PRIMITIVE METHOD 21 | 22 | abstract boolean endOfGame(); // PRIMITIVE METHOD 23 | 24 | abstract void printWinner(); // PRIMITIVE METHOD 25 | } 26 | 27 | class Monopoly extends Game { 28 | void initializeGame() { 29 | // ... 30 | } 31 | 32 | void makePlay(int player) { 33 | // ... 34 | } 35 | 36 | boolean endOfGame() { 37 | // ... 38 | } 39 | 40 | void printWinner() { 41 | // ... 42 | } 43 | } 44 | 45 | class ChessGame extends Game { 46 | void initializeGame() { 47 | // ... 48 | } 49 | 50 | void makePlay(int player) { 51 | // ... 52 | } 53 | 54 | boolean endOfGame() { 55 | // ... 56 | } 57 | 58 | void printWinner() { 59 | // ... 60 | } 61 | } 62 | 63 | public class GameApp { 64 | 65 | public static void main(String[] args) { 66 | // TODO Auto-generated method stub 67 | 68 | } 69 | } 70 | -------------------------------------------------------------------------------- /src/basic/javainheritance/PolymorphismDemo.java: -------------------------------------------------------------------------------- 1 | package basic.javainheritance; 2 | 3 | /** 4 | * Using Sale and Discount classes to demo late binding and Polymorphism 5 | */ 6 | public class PolymorphismDemo { 7 | public static void main(String[] args) 8 | { 9 | Sale simple = new Sale("floor mat", 10.00);//One item at $10.00. 10 | DiscountSale discount = new DiscountSale("floor mat", 11.00, 10); 11 | //One item at $11.00 with a 10% discount. 12 | System.out.println(simple); 13 | System.out.println(discount); 14 | 15 | if (discount.lessThan(simple)) 16 | System.out.println("Discounted item is cheaper."); 17 | else 18 | System.out.println("Discounted item is not cheaper."); 19 | 20 | Sale regularPrice = new Sale("cup holder", 9.90);//One item at $9.90. 21 | DiscountSale specialPrice = new DiscountSale("cup holder", 11.00, 10); 22 | //One item at $11.00 with a 10% discount. 23 | System.out.println(regularPrice); 24 | System.out.println(specialPrice); 25 | 26 | if (specialPrice.equalDeals(regularPrice)) 27 | System.out.println("Deals are equal."); 28 | else 29 | System.out.println("Deals are not equal."); 30 | } 31 | } 32 | 33 | 34 | -------------------------------------------------------------------------------- /src/iterator/IterationDemo.java: -------------------------------------------------------------------------------- 1 | package iterator; 2 | 3 | import java.util.*; 4 | 5 | public class IterationDemo { 6 | 7 | public static void main(String[] args) { 8 | // Vector並且增加內容 9 | Vector v = new Vector(); 10 | v.addElement(new String("Hello")); 11 | v.addElement(new String("Taichung")); 12 | v.addElement(new String("Have a nice day")); 13 | // 瀏覽 Vector內的內容 14 | Iterator it1 = v.iterator(); 15 | System.out.print("Vector 內的內容為:"); 16 | traverse(it1); 17 | 18 | // ArrayList 19 | ArrayList v2 = new ArrayList(); 20 | v2.add(new String("Hello")); 21 | v2.add(new String("Taipei")); 22 | v2.add(new String("Good morning")); 23 | // 瀏覽 ArrayList 內的內容 24 | Iterator it2 = v2.iterator(); 25 | System.out.print("\nArrayList 內的內容為:"); 26 | traverse(it2); 27 | 28 | // HashMap 29 | HashMap v3 = new HashMap(); 30 | v3.put("John", new Integer(172)); 31 | v3.put("Mary", new Integer(168)); 32 | v3.put("Nick", new Integer(180)); 33 | // 瀏覽 HashMap 的 Key 34 | Iterator it3 = v3.keySet().iterator(); 35 | System.out.print("\nHashMap 內的內容為:"); 36 | traverse(it3); 37 | } 38 | 39 | static void traverse(Iterator e) { 40 | while (e.hasNext()) { 41 | System.out.print(e.next() + ", "); 42 | } 43 | } 44 | 45 | } 46 | -------------------------------------------------------------------------------- /src/composite/CompositeTemplate.java: -------------------------------------------------------------------------------- 1 | package composite; 2 | 3 | public class CompositeTemplate { 4 | public static void main(String args[]) { 5 | //just for demo 6 | Composite c1 = new Composite(); 7 | c1.addComponent(new Leaf("J")); 8 | c1.addComponent(new Leaf("K")); 9 | c1.op(); 10 | 11 | Composite c2 = new Composite(); 12 | c2.addComponent(c1); 13 | c2.addComponent(new Leaf("Q")); 14 | c2.op(); 15 | } 16 | } 17 | 18 | // COMPONENT 19 | abstract class Component { 20 | abstract void op(); //OPERATION 21 | } 22 | 23 | // COMPOSITE 24 | class Composite extends Component { 25 | ArrayList list; 26 | String name; 27 | 28 | public Composite(String n) { 29 | this.name = n; 30 | list = new ArrayList(); 31 | } 32 | 33 | void addComponent(Component c) { 34 | list.add(c); 35 | } 36 | 37 | // OPERATION in COMPOSITE 38 | void op() { 39 | ListerIterator iterator = list.listIterator(); 40 | while (iterator.hasNext()) { 41 | Component c = iterator.next(); 42 | c.op(); 43 | } 44 | } 45 | System.out.println(name); 46 | } 47 | 48 | // LEAF 49 | class Leaf extends Component { 50 | String name; 51 | 52 | public Leaf(String a) { 53 | name = a; 54 | } 55 | 56 | // OPERATION in LEAF 57 | void op() { 58 | System.out.println(name); 59 | } 60 | } -------------------------------------------------------------------------------- /src/uml/GradeBookApp0.java: -------------------------------------------------------------------------------- 1 | /* 2 | CLASSES and attributes, operations 3 | A gradebook application, the basic classes are: 4 | * Students 5 | * Course 6 | * Teacher 7 | 8 | * if we don't want other class to modify the email directly 9 | we should set the email attribute to "private" 10 | */ 11 | 12 | public class GradeBookApp0 { 13 | public static void main(String args[]) { 14 | Student Jie = new Student ("Jie"); 15 | Student Albert = new Student ("Albert"); 16 | Jie.setEmail("jie@mail.com"); 17 | Albert.setEmail("albert@mail.com"); 18 | Jie.email = "xx@gmail.com"; 19 | System.out.println(Jie.email); 20 | Teacher Nick = new Teacher ("Nick"); 21 | Course Java = new Course ("Java", 3); 22 | Course Python = new Course ("Python", 3); 23 | } 24 | } 25 | 26 | class Course { 27 | String cName; 28 | private int degree; 29 | public Course (String name, int degree) { 30 | this.cName = name; 31 | this.degree = degree; 32 | } 33 | } 34 | 35 | class Teacher { 36 | String tName; 37 | String email; 38 | public Teacher(String name) { 39 | this.tName = name; 40 | } 41 | public void setEmail(String e) { 42 | this.email = e; 43 | } 44 | } 45 | 46 | class Student { 47 | String sName; 48 | String email; 49 | public Student (String name){ 50 | this.sName = name; 51 | } 52 | public void setEmail(String e) { 53 | this.email = e; 54 | } 55 | } -------------------------------------------------------------------------------- /src/cor/CoRDemo.java: -------------------------------------------------------------------------------- 1 | package cor; 2 | 3 | import java.util.Random; 4 | 5 | public class CoRDemo { 6 | 7 | public static void main(String[] args) { 8 | Handler h2 = new Handler2(null); 9 | Handler h1 = new Handler1(h2); 10 | 11 | // 第一個處理者都是 Handler1 12 | h1.handleRequest(100); 13 | h1.handleRequest(0); 14 | h1.handleRequest(10); 15 | } 16 | } 17 | 18 | abstract class Handler { 19 | Handler successor; 20 | 21 | public Handler(Handler h) { 22 | successor = h; 23 | } 24 | 25 | public void handleRequest(int i) { 26 | if (successor != null) 27 | successor.handleRequest(i); 28 | else 29 | System.out.println("No one can handle it"); 30 | } 31 | } 32 | 33 | class Handler1 extends Handler { 34 | Random rn = new Random(); 35 | public Handler1(Handler h) { 36 | super(h); 37 | } 38 | 39 | public void handleRequest(int x) { 40 | int i = rn.nextInt(2); 41 | 42 | // Handler 依據請求的參數值及自身的狀態來決定是否能夠處理 43 | if (x > 10 || (i==1)) 44 | System.out.println("Handler 1 will handle"); 45 | else 46 | // 不能處理時就丟給下一個 47 | super.handleRequest(x); 48 | } 49 | } 50 | 51 | class Handler2 extends Handler { 52 | public Handler2(Handler h) { 53 | super(h); 54 | } 55 | 56 | public void handleRequest(int x) { 57 | if (x < 10) 58 | System.out.println("Handler 2 will handle"); 59 | else 60 | super.handleRequest(x); 61 | } 62 | } 63 | -------------------------------------------------------------------------------- /src/observer/noapi/ObserverNoAPI.java: -------------------------------------------------------------------------------- 1 | package observer.noapi; 2 | 3 | import java.util.Vector; 4 | 5 | public class ObserverNoAPI { 6 | public static void main(String[] arg) { 7 | } 8 | } 9 | 10 | class Client { 11 | void testObserver() { 12 | ConcreteSubject subject = new ConcreteSubject(); 13 | ConcreteObserver observer = new ConcreteObserver(); 14 | subject.addObserver(observer); 15 | subject.setState(new Integer(12)); 16 | subject.setState(new Integer(23)); 17 | } 18 | } 19 | 20 | abstract class Subject { 21 | private Vector observers; 22 | 23 | protected void addObserver(Observer o) { 24 | observers.add(o); 25 | } 26 | 27 | protected void notifyObservers() { 28 | for (Observer o : observers) 29 | o.update(this); 30 | } 31 | } 32 | 33 | class ConcreteSubject extends Subject { 34 | private Object subjectState; 35 | 36 | public Object getState() { 37 | return subjectState; 38 | } 39 | 40 | void setState(Object newState) { 41 | subjectState = newState; 42 | notifyObservers(); 43 | } 44 | } 45 | 46 | interface Observer { 47 | public void update(Subject s); 48 | } 49 | 50 | class ConcreteObserver implements Observer { 51 | public void update(Subject s) { 52 | try { 53 | ConcreteSubject cs = (ConcreteSubject) s; 54 | System.out.println("Updated: " + cs.getState()); 55 | } catch (Exception e) { 56 | System.err.println("type mismatch"); 57 | } 58 | } 59 | } -------------------------------------------------------------------------------- /src/state/StateDemo.java: -------------------------------------------------------------------------------- 1 | package state; 2 | 3 | public class StateDemo { 4 | 5 | /** 6 | * @param args 7 | */ 8 | public static void main(String[] args) { 9 | A a = new A(); 10 | System.out.println(a); 11 | a.request(); 12 | System.out.println(a); 13 | a.request(); 14 | System.out.println(a); 15 | a.request(); 16 | System.out.println(a); 17 | a.request(); 18 | System.out.println(a); 19 | } 20 | } 21 | 22 | class A { 23 | State s; 24 | 25 | // the default state is S1 26 | public A() { 27 | s = new S1(); 28 | } 29 | 30 | public void request() { 31 | s.handleRequest(this); 32 | } 33 | 34 | void setState(State _s) { 35 | this.s = _s; 36 | } 37 | 38 | public String toString() { 39 | return s.toString(); 40 | } 41 | 42 | } 43 | 44 | abstract class State { 45 | abstract public void handleRequest(A a); 46 | } 47 | 48 | class S1 extends State { 49 | 50 | @Override 51 | public void handleRequest(A a) { 52 | a.setState(new S2()); 53 | } 54 | 55 | public String toString() { 56 | return "S1"; 57 | } 58 | } 59 | 60 | class S2 extends State { 61 | public void handleRequest(A a) { 62 | a.setState(new S3()); 63 | } 64 | 65 | public String toString() { 66 | return "S2"; 67 | } 68 | 69 | } 70 | 71 | class S3 extends State { 72 | public void handleRequest(A a) { 73 | a.setState(new S1()); 74 | } 75 | 76 | public String toString() { 77 | return "S3"; 78 | } 79 | 80 | } 81 | -------------------------------------------------------------------------------- /src/basic/javainheritance/BicycleDemo.java: -------------------------------------------------------------------------------- 1 | package basic.javainheritance; 2 | 3 | class Bicycle { 4 | 5 | // the Bicycle class has three fields 6 | public int cadence; 7 | public int gear; 8 | public int speed; 9 | 10 | // the Bicycle class has one constructor 11 | public Bicycle(int startCadence, int startSpeed, int startGear) { 12 | gear = startGear; 13 | cadence = startCadence; 14 | speed = startSpeed; 15 | } 16 | 17 | // the Bicycle class has four methods 18 | public void setCadence(int newValue) { 19 | cadence = newValue; 20 | } 21 | 22 | public void setGear(int newValue) { 23 | gear = newValue; 24 | } 25 | 26 | public void applyBrake(int decrement) { 27 | speed -= decrement; 28 | } 29 | 30 | public void speedUp(int increment) { 31 | speed += increment; 32 | } 33 | 34 | } 35 | 36 | class MountainBike extends Bicycle { 37 | 38 | // the MountainBike subclass adds one field 39 | public int seatHeight; 40 | 41 | // the MountainBike subclass has one constructor 42 | public MountainBike(int startHeight, int startCadence, int startSpeed, 43 | int startGear) { 44 | super(startCadence, startSpeed, startGear); 45 | seatHeight = startHeight; 46 | } 47 | 48 | // the MountainBike subclass adds one method 49 | public void setHeight(int newValue) { 50 | seatHeight = newValue; 51 | } 52 | } 53 | 54 | public class BicycleDemo { 55 | public static void main(String[] arg) { 56 | 57 | } 58 | 59 | } 60 | -------------------------------------------------------------------------------- /src/chess/chessv5/ChessBoarding.java: -------------------------------------------------------------------------------- 1 | package chess.chessv5; 2 | 3 | /* 4 | * 設定棋子位置的方法。Strategy 設計樣式中的 AbstractStrategy 5 | */ 6 | interface ChessBoarding { 7 | public void setLocation(Chess[] chesses); 8 | } 9 | 10 | /* 11 | * 隨機的設定棋子的位置 12 | */ 13 | class RandomChessBoarding implements ChessBoarding { 14 | 15 | public void setLocation(Chess[] chesses) { 16 | // initialize location 17 | for (int i = 0; i < chesses.length; i++) { 18 | chesses[i].setLoc(i); 19 | } 20 | // exchange location 21 | for (int i = 0; i < chesses.length / 2; i++) { 22 | int a = (int) (Math.random() * 32); 23 | int b = (int) (Math.random() * 32); 24 | Chess chessA = chesses[a]; 25 | Chess chessB = chesses[b]; 26 | int chessALocation = chessA.getLoc(); 27 | // switch the location 28 | chessA.setLoc(chessB.getLoc()); 29 | chessB.setLoc(chessALocation); 30 | } 31 | } 32 | } 33 | 34 | /* 35 | * Side by side 36 | */ 37 | class SideBySideChessBoarding implements ChessBoarding { 38 | public void setLocation(Chess[] chesses) { 39 | for (int i = 0; i < chesses.length / 2; i++) { 40 | chesses[i].setLoc(i * 2); 41 | chesses[i + 16].setLoc(i * 2 + 1); 42 | } 43 | } 44 | } 45 | 46 | /* 47 | * 簡易的棋子排版,會依照 將士...卒帥仕...兵 的方式排版 48 | */ 49 | class SimpleChessBoarding implements ChessBoarding { 50 | public void setLocation(Chess[] chesses) { 51 | for (int i = 0; i < chesses.length; i++) { 52 | chesses[i].setLoc(i); 53 | } 54 | } 55 | } 56 | -------------------------------------------------------------------------------- /src/adaptor/AdaptorApp01.java: -------------------------------------------------------------------------------- 1 | import java.util.Enumeration; 2 | import java.util.Iterator; 3 | import java.util.Vector; 4 | 5 | /* 6 | Group 用 Vector 來儲存一群成績 7 | */ 8 | class Group { 9 | Vector grade; 10 | 11 | public Group() { 12 | grade = new Vector(); 13 | grade.add(80); 14 | grade.add(80); 15 | grade.add(70); 16 | grade.add(90); 17 | } 18 | 19 | Enumeration getGrade() { 20 | return grade.elements(); 21 | } 22 | } 23 | 24 | /* 25 | * School 用 Iterator 來計算平均 26 | */ 27 | class School { 28 | public static double getAverage(Iterator it) { 29 | double avg = 0, sum = 0, count = 0; 30 | 31 | // YOU CODE HERE 32 | 33 | return avg; 34 | } 35 | } 36 | 37 | /* 38 | * Adaptor. YOU CODE HERE 39 | */ 40 | class GradeIterator implements Iterator { 41 | Enumeration gradeList; 42 | 43 | public GradeIterator(Enumeration e) { 44 | // YOU CODE HERE 45 | } 46 | 47 | public boolean hasNext() { 48 | // YOU CODE HERE 49 | } 50 | 51 | public E next() { 52 | // YOU CODE HERE 53 | } 54 | 55 | public void remove() { 56 | // enumeration can't remove element 57 | } 58 | } 59 | 60 | public class AdaptorApp01 { 61 | 62 | public static void main(String[] args) { 63 | Group g = new Group(); 64 | Enumeration e = g.getGrade(); 65 | 66 | // 建立一個 adaptor 67 | // YOU CODE HERE 68 | 69 | // 傳給 School 來計算 70 | // YOU CODE HERE 71 | System.out.println(average); 72 | } 73 | 74 | } -------------------------------------------------------------------------------- /src/hw/CompositeDemo.java: -------------------------------------------------------------------------------- 1 | package hw; 2 | 3 | import java.util.ArrayList; 4 | import java.util.Iterator; 5 | 6 | public class CompositeDemo { 7 | 8 | /** 9 | * @param args 10 | */ 11 | public static void main(String[] args) { 12 | 13 | Question q1 = new Question("1+1="); 14 | Question q2 = new Question("1+2="); 15 | Question q3 = new Question("1+3="); 16 | 17 | Paper p1 = new Paper(); 18 | p1.add(q1); 19 | p1.add(q2); 20 | p1.add(q3); 21 | p1.showQuestion(); 22 | 23 | Question q4 = new Question("2+1="); 24 | 25 | Paper p2 = new Paper(); 26 | p2.add(p1); 27 | p2.add(q4); 28 | 29 | p2.showQuestion(); 30 | 31 | } 32 | 33 | } 34 | 35 | interface IPaper { 36 | void showQuestion(); 37 | } 38 | 39 | class Question implements IPaper { 40 | String description; 41 | 42 | public Question(String s) { 43 | description = s; 44 | } 45 | 46 | public void showQuestion() { 47 | // TODO Auto-generated method stub 48 | System.out.println(description); 49 | } 50 | 51 | } 52 | 53 | class Paper implements IPaper { 54 | ArrayList papers = new ArrayList(); 55 | 56 | public void showQuestion() { 57 | // Iterator it = papers.iterator(); 58 | // while (it.hasNext()) { 59 | // IPaper p = (IPaper) it.next(); 60 | // p.showQuestion(); 61 | // } 62 | for (IPaper p: papers) { 63 | p.showQuestion(); 64 | } 65 | 66 | 67 | } 68 | 69 | public void add(IPaper p) { 70 | papers.add(p); 71 | } 72 | 73 | } 74 | 75 | -------------------------------------------------------------------------------- /src/factorymethod/FactoryMethodApp01.java: -------------------------------------------------------------------------------- 1 | import java.util.Scanner; 2 | 3 | abstract class Doc { 4 | protected String content; 5 | 6 | abstract public void save(String word); 7 | abstract void show(); 8 | } 9 | 10 | class TextDoc extends Doc { 11 | //just a simulation, using textDoc approach to 12 | // save file 13 | public void save(String word) { 14 | content = word; 15 | } 16 | 17 | public void show() { 18 | System.out.println("Text Doc shows: " + content); 19 | } 20 | } 21 | 22 | class WordDoc extends Doc { 23 | //just a simulation, using wordDoc approach to 24 | // save file 25 | public void save(String word) { 26 | content = "**" + word + "**"; 27 | } 28 | 29 | public void show() { 30 | System.out.println("Word Doc shows: " + content); 31 | } 32 | } 33 | 34 | abstract class App { 35 | public void readToFile() { 36 | Doc d; 37 | Scanner sc = new Scanner(System.in); 38 | System.out.println("Please input your name:"); 39 | String name = sc.nextLine(); 40 | 41 | d = createDoc(); 42 | d.save(name); 43 | d.show(); 44 | } 45 | 46 | abstract public Doc createDoc(); 47 | } 48 | 49 | 50 | 51 | // YOU CODE HERE 52 | class TextApp extends App { 53 | 54 | } 55 | 56 | class WordApp extends App { 57 | 58 | } 59 | 60 | 61 | public class FactoryMethodApp01 { 62 | 63 | public static void main(String[] args) { 64 | 65 | App textApp = new TextApp(); 66 | textApp.readToFile(); 67 | 68 | // YOU CODE HERE, create a wordApp 69 | } 70 | } 71 | 72 | 73 | 74 | 75 | 76 | 77 | -------------------------------------------------------------------------------- /src/composite/CompositeApp01.java: -------------------------------------------------------------------------------- 1 | import java.util.ArrayList; 2 | import java.util.ListIterator; 3 | 4 | // COMPONENT 5 | abstract class AbstractFile { 6 | // ONE LINE CODE 7 | } 8 | 9 | // COMPOSITE 10 | class Folder extends AbstractFile { 11 | ArrayList elements; 12 | 13 | public Folder() { 14 | elements = new ArrayList(); 15 | } 16 | 17 | void add(AbstractFile c) { 18 | elements.add(c); 19 | } 20 | 21 | // OPERATION in COMPOSITE 22 | int getSize() { 23 | // YOU CODE HERE 24 | return size; 25 | } 26 | } 27 | 28 | // LEAF 29 | class TextFile extends AbstractFile { 30 | int size; 31 | 32 | public TextFile(int s) { 33 | this.size = s; 34 | } 35 | 36 | // OPERATION in LEAF 37 | int getSize() { 38 | // ONE LINE CODE 39 | } 40 | } 41 | 42 | 43 | // LEAF 44 | class ZipFile extends AbstractFile { 45 | int size; 46 | double rate; 47 | 48 | public ZipFile(int size, double rate) { 49 | // YOU CODE HERE 50 | } 51 | 52 | // OPERATION in LEAF 53 | int getSize() { 54 | return (int) (size * rate); 55 | } 56 | } 57 | 58 | public class CompositeApp02 { 59 | public static void main(String[] args) { 60 | Folder f1 = new Folder(); 61 | f1.add(new TextFile(120)); 62 | System.out.println(f1.getSize()); 63 | 64 | TextFile text = new TextFile(1200); 65 | ZipFile zipFile = new ZipFile(900, 0.4); 66 | 67 | Folder f2 = new Folder(); 68 | f2.add(text); 69 | f2.add(zipFile); 70 | f2.add(f1); 71 | 72 | System.out.println(f2.getSize()); 73 | } 74 | } -------------------------------------------------------------------------------- /src/sandbox/TestIterator.java: -------------------------------------------------------------------------------- 1 | package sandbox; 2 | 3 | import java.util.ArrayList; 4 | import java.util.Iterator; 5 | import java.util.ListIterator; 6 | 7 | public class TestIterator { 8 | 9 | public static void main(String[] args) { 10 | 11 | Question q1 = new Question("1+1="); 12 | Question q2 = new Question("1+2="); 13 | Question q3 = new Question("1+3="); 14 | 15 | Paper p1 = new Paper(); 16 | p1.add(q1); 17 | p1.add(q2); 18 | p1.add(q3); 19 | p1.showQuestion(); 20 | 21 | // Question q4 = new Question("2+1="); 22 | // 23 | // Paper p2 = new Paper(); 24 | // p2.add(p1); 25 | // p2.add(q4); 26 | // 27 | // p2.showQuestion(); 28 | 29 | } 30 | 31 | } 32 | 33 | interface IPaper { 34 | void showQuestion(); 35 | } 36 | 37 | class Question implements IPaper { 38 | String description; 39 | 40 | public Question(String s) { 41 | description = s; 42 | } 43 | 44 | public void showQuestion() { 45 | // TODO Auto-generated method stub 46 | System.out.println(description); 47 | } 48 | 49 | } 50 | 51 | class Paper implements IPaper { 52 | ArrayList papers; 53 | 54 | public Paper() { 55 | papers = new ArrayList(); 56 | } 57 | 58 | public void showQuestion() { 59 | // ListIterator it = papers.listIterator(); 60 | // Iterator it = papers.iterator(); 61 | // while (it.hasNext()) { 62 | // System.out.println(it.nextIndex()); 63 | // IPaper p = (IPaper) it.next(); 64 | // p.showQuestion(); 65 | // } 66 | for (IPaper p : papers) { 67 | p.showQuestion(); 68 | } 69 | 70 | } 71 | 72 | public void add(IPaper p) { 73 | papers.add(p); 74 | } 75 | } 76 | -------------------------------------------------------------------------------- /src/refactoring/TriangleTest.java: -------------------------------------------------------------------------------- 1 | package refactoring; 2 | 3 | import static org.junit.Assert.*; 4 | 5 | import org.junit.Assert; 6 | import org.junit.Test; 7 | 8 | public class TriangleTest { 9 | 10 | @Test 11 | public void testGetType() { 12 | // fail("Not yet implemented"); 13 | 14 | String expected = "���T����"; 15 | Triangle t1 = new Triangle(10, 10, 10); 16 | Assert.assertEquals(expected, t1.getType()); 17 | 18 | expected = "���y�T����"; 19 | Triangle t2 = new Triangle(10, 10, 18); 20 | Assert.assertEquals(expected, t2.getType()); 21 | t2 = new Triangle(18, 10, 10); 22 | Assert.assertEquals(expected, t2.getType()); 23 | t2 = new Triangle(10, 18, 10); 24 | Assert.assertEquals("���y�T����", t2.getType()); 25 | 26 | expected = "�����T����"; 27 | Triangle t3 = new Triangle(3, 4, 5); 28 | Assert.assertEquals(expected, t3.getType()); 29 | t3 = new Triangle(5, 4, 3); 30 | Assert.assertEquals(expected, t3.getType()); 31 | t3 = new Triangle(4, 5, 3); 32 | Assert.assertEquals(expected, t3.getType()); 33 | 34 | expected = "�@��T����"; 35 | Triangle t4 = new Triangle(3, 4, 6); 36 | Assert.assertEquals(expected, t4.getType()); 37 | t4 = new Triangle(4, 6, 3); 38 | Assert.assertEquals(expected, t4.getType()); 39 | t4 = new Triangle(6, 3, 4); 40 | Assert.assertEquals(expected, t4.getType()); 41 | 42 | expected = "���O�T����"; 43 | Triangle t5 = new Triangle(1, 1, 3); 44 | Assert.assertEquals(expected, t5.getType()); 45 | t5 = new Triangle(3, 1, 1); 46 | Assert.assertEquals(expected, t5.getType()); 47 | t5 = new Triangle(1, 3, 1); 48 | Assert.assertEquals(expected, t5.getType()); 49 | 50 | //Assert. 51 | 52 | } 53 | 54 | } 55 | -------------------------------------------------------------------------------- /src/abstractfactory/MazeGameDemo.java: -------------------------------------------------------------------------------- 1 | package abstractfactory; 2 | 3 | public class MazeGameDemo { 4 | 5 | public static void main(String[] args) { 6 | MazeGame mg = new MazeGame(); 7 | mg.createMaze(); 8 | 9 | MazeGame mg2 = new GhostMazeGame(); 10 | mg2.createMaze(); 11 | } 12 | 13 | } 14 | 15 | class MazeGame { 16 | 17 | Maze maze; 18 | Door door; 19 | Wall wall; 20 | 21 | public void createMaze() { 22 | maze = makeMaze(); 23 | door = makeDoor(); 24 | wall = makeWall(); 25 | } 26 | 27 | //factory method 28 | protected Wall makeWall() { 29 | return new Wall(); 30 | } 31 | 32 | //factory method 33 | protected Door makeDoor() { 34 | return new Door(); 35 | } 36 | 37 | //factory method 38 | protected Maze makeMaze() { 39 | return new Maze(); 40 | } 41 | } 42 | 43 | class GhostMazeGame extends MazeGame { 44 | //factory method 45 | protected Wall makeWall() { 46 | return new GhostWall(); 47 | } 48 | 49 | //factory method 50 | protected Door makeDoor() { 51 | // TODO Auto-generated method stub 52 | return new GhostDoor(); 53 | } 54 | 55 | //factory method 56 | protected Maze makeMaze() { 57 | // TODO Auto-generated method stub 58 | return new GhostMaze(); 59 | } 60 | 61 | } 62 | 63 | class Maze { 64 | public Maze() { 65 | System.out.println(this); 66 | 67 | } 68 | } 69 | 70 | class Wall { 71 | public Wall() { 72 | System.out.println(this); 73 | 74 | } 75 | } 76 | 77 | class Door { 78 | public Door() { 79 | System.out.println(this); 80 | } 81 | } 82 | 83 | class GhostMaze extends Maze { 84 | 85 | } 86 | 87 | class GhostDoor extends Door { 88 | 89 | } 90 | 91 | class GhostWall extends Wall { 92 | 93 | } 94 | -------------------------------------------------------------------------------- /src/uml/GradeBookApp1.java: -------------------------------------------------------------------------------- 1 | /* 2 | many-to-one ASSOCIATION 3 | "Offer" relationship between Teacher and Course 4 | * the 1-* is implemented by a simple array. I know it is 5 | not a good way. Later version will be better. 6 | 7 | * Teacher can "navigate" the Course, but Course can't 8 | naviate the Teacher (one way navigation) 9 | */ 10 | 11 | public class GradeBookApp1 { 12 | public static void main(String args[]) { 13 | Student Jie = new Student ("Jie"); 14 | Student Albert = new Student ("Albert"); 15 | 16 | Teacher Nick = new Teacher ("Nick"); 17 | 18 | Course Java = new Course ("Java", 3); 19 | Course Python = new Course ("Python", 3); 20 | 21 | Nick.offer(Java); //++++++++++ 22 | Nick.offer(Python); //++++++++++ 23 | Nick.showCourse(); //++++++++++ 24 | } 25 | 26 | } 27 | 28 | class Course { 29 | String cName; 30 | private int degree; 31 | public Course (String name, int degree) { 32 | this.cName = name; 33 | this.degree = degree; 34 | } 35 | } 36 | 37 | class Teacher { 38 | String tName; 39 | private String email; 40 | Course[] courses = new Course[10]; //++++++++++ 41 | int couseCount = 0; //++++++++++ 42 | public Teacher(String name) { 43 | this.tName = name; 44 | } 45 | public void setEmail(String e) { 46 | this.email = e; 47 | } 48 | public void offer(Course c) { //++++++++++ 49 | courses[couseCount++] = c; 50 | } 51 | 52 | public void showCourse() { //++++++++++ 53 | for (Course c: courses) { 54 | if (c != null) 55 | System.out.println(c.cName); 56 | else 57 | break; 58 | } 59 | } 60 | } 61 | 62 | class Student { 63 | String sName; 64 | private String email; 65 | public Student (String name){ 66 | this.sName = name; 67 | } 68 | public void setEmail(String e) { 69 | this.email = e; 70 | } 71 | } -------------------------------------------------------------------------------- /src/principle/LampDemo.java: -------------------------------------------------------------------------------- 1 | public class LampDemo { 2 | public static void main(String args[]) { 3 | ButtonClient lamp = new Lamp(); 4 | Button b = new Button(lamp); //開關控制檯燈 5 | b.turnOn(); 6 | b.turnOff(); 7 | b.turnOn(); 8 | 9 | ButtonClient ac = new AC(); 10 | b = new Button(ac); //可以換成控制冷氣機 11 | ((AC)ac).setDegree(30); 12 | b.turnOn(); 13 | b.turnOff(); 14 | ((AC)ac).setDegree(21); 15 | b.turnOn(); 16 | } 17 | } 18 | 19 | // 開關按鈕的對象(小家電) 20 | abstract class ButtonClient { 21 | public abstract void turnOn(); 22 | public abstract void turnOff(); 23 | } 24 | 25 | // 開關按鈕,Button,相依於一個抽象通用的 ButtonClient 26 | class Button { 27 | private ButtonClient bClient; 28 | public Button(ButtonClient b) { //連結真實的 ButtonClient 29 | bClient = b; 30 | } 31 | public void turnOn() { 32 | bClient.turnOn(); 33 | } 34 | public void turnOff() { 35 | bClient.turnOff(); 36 | } 37 | } 38 | 39 | // Lamp 自己定義開關 40 | class Lamp extends ButtonClient { 41 | String state="off"; 42 | public void turnOn() { 43 | state = "on"; 44 | printState(); 45 | } 46 | public void turnOff() { 47 | state = "off"; 48 | printState(); 49 | } 50 | private void printState() { 51 | System.out.println("Lamp is " + state); 52 | } 53 | } 54 | 55 | // 冷氣機 自己定義開關 56 | class AC extends ButtonClient { 57 | int currentDegree = 28; 58 | String state="off"; 59 | 60 | // 高於 28 度才可以開啟 61 | public void turnOn() { 62 | if (currentDegree > 28) { 63 | state = "on"; 64 | } 65 | printState(); 66 | } 67 | public void turnOff() { 68 | state = "off"; 69 | printState(); 70 | } 71 | private void printState() { 72 | System.out.println("AC is " + state); 73 | } 74 | public void setDegree(int d) { 75 | this.currentDegree = d; 76 | } 77 | } -------------------------------------------------------------------------------- /src/principle/LSP/LSPDemo.java: -------------------------------------------------------------------------------- 1 | /* 2 | * To demo the Liskov Substitution Principle (LSP) 3 | * - the subclass "Square" should behavior like a "Rectangle", 4 | * but it does not! 5 | */ 6 | package principle.LSP; 7 | 8 | public class LSPDemo { 9 | 10 | public static void main(String[] args) { 11 | 12 | Rectangle r = new Rectangle(1, 1); 13 | Square s = new Square(1); 14 | testLSP(r); 15 | testLSP(s); 16 | } 17 | 18 | public static void testLSP(Rectangle r) { 19 | r.setHeight(10); 20 | r.setWeight(2); 21 | 22 | if (r.getArea() != 20) { 23 | System.out.println(r.toString() + ", Wrong area!"); 24 | } else { 25 | System.out.println(r.toString() + ", Great"); 26 | } 27 | } 28 | 29 | } 30 | 31 | class Rectangle { 32 | int weight; 33 | int height; 34 | 35 | public int getWeight() { 36 | return weight; 37 | } 38 | 39 | public void setWeight(int weight) { 40 | this.weight = weight; 41 | } 42 | 43 | public int getHeight() { 44 | return height; 45 | } 46 | 47 | public Rectangle(int w, int h) { 48 | this.weight = w; 49 | this.height = h; 50 | } 51 | 52 | public void setHeight(int h) { 53 | this.height = h; 54 | } 55 | 56 | public int getArea() { 57 | return this.height * this.weight; 58 | } 59 | 60 | public String toString() { 61 | return "Rectangle, h = " + this.height + ", w " + this.weight; 62 | } 63 | } 64 | 65 | class Square extends Rectangle { 66 | 67 | public Square(int w, int h) { 68 | super(w, h); 69 | } 70 | 71 | public Square(int i) { 72 | super(i, i); 73 | } 74 | 75 | public void setHeight(int h) { 76 | super.setHeight(h); 77 | super.setWeight(h); 78 | } 79 | 80 | public void setWeight(int w) { 81 | super.setHeight(w); 82 | super.setWeight(w); 83 | } 84 | 85 | public String toString() { 86 | return "Square, h = " + super.getHeight() + ", w " + super.getWeight(); 87 | } 88 | } -------------------------------------------------------------------------------- /src/abstractfactory/FactoryDemo.java: -------------------------------------------------------------------------------- 1 | package abstractfactory; 2 | 3 | public class FactoryDemo { 4 | public static void main(String[] args) { 5 | // TODO Auto-generated method stub 6 | ShoesFactory sf = new LeatherShoesFactory(); 7 | makeShoes(sf); 8 | 9 | System.out.println(); 10 | 11 | ShoesFactory sf2 = new SportShoesFactory(); 12 | makeShoes(sf2); 13 | 14 | } 15 | 16 | public static void makeShoes(ShoesFactory f) { 17 | System.out.println(f.makeShoesBody()); 18 | System.out.println(f.makeShoesBottom()); 19 | System.out.println(f.makeShoesStrap()); 20 | } 21 | } 22 | 23 | class ShoesBody { 24 | } 25 | 26 | class ShoesBottom{ 27 | } 28 | 29 | class ShoesStrap{ 30 | } 31 | 32 | class SportShoesBody extends ShoesBody{ 33 | } 34 | 35 | class SportShoesStrap extends ShoesStrap{ 36 | } 37 | 38 | class SportShoesBottom extends ShoesBottom{ 39 | } 40 | 41 | class LeatherShoesBody extends ShoesBody{ 42 | } 43 | 44 | class LeatherShoesStrap extends ShoesStrap{ 45 | } 46 | 47 | class LeatherShoesBottom extends ShoesBottom{ 48 | } 49 | 50 | interface ShoesFactory { 51 | public ShoesBody makeShoesBody(); 52 | public ShoesBottom makeShoesBottom(); 53 | public ShoesStrap makeShoesStrap(); 54 | 55 | } 56 | 57 | class SportShoesFactory implements ShoesFactory { 58 | public ShoesBody makeShoesBody() { 59 | return new SportShoesBody(); 60 | } 61 | 62 | public ShoesBottom makeShoesBottom() { 63 | return new SportShoesBottom(); 64 | } 65 | public ShoesStrap makeShoesStrap() { 66 | return new SportShoesStrap(); 67 | } 68 | } 69 | 70 | class LeatherShoesFactory implements ShoesFactory { 71 | public ShoesBody makeShoesBody() { 72 | return new LeatherShoesBody(); 73 | } 74 | 75 | public ShoesBottom makeShoesBottom() { 76 | return new LeatherShoesBottom(); 77 | } 78 | public ShoesStrap makeShoesStrap() { 79 | return new LeatherShoesStrap(); 80 | } 81 | } -------------------------------------------------------------------------------- /src/mediator/template/MediatorTemplate.java: -------------------------------------------------------------------------------- 1 | package mediator.template; 2 | 3 | public class MediatorTemplate { 4 | 5 | public static void main(String[] args) { 6 | IMediator med = new Mediator(); 7 | 8 | // 生成 colleague 時,設定其 Mediator 9 | Colleague1 c1 = new Colleague1(med); 10 | Colleague2 c2 = new Colleague2(med); 11 | 12 | // 送訊息給 c1, c2 13 | c1.m1(); 14 | c2.m2(); 15 | } 16 | } 17 | 18 | interface IMediator { 19 | void m1(); 20 | 21 | void m2(); 22 | 23 | void registerColleague1(Colleague1 c); 24 | 25 | void registerColleague2(Colleague2 c); 26 | } 27 | 28 | class Mediator implements IMediator { 29 | Colleague1 c1; 30 | Colleague2 c2; 31 | 32 | // 雖然 m1 是給 Colleague1 的訊息,但會轉給 mediator 33 | // mediator 來決定會與哪些其他 Colleague 互動 34 | public void m1() { 35 | System.out.println("Mediator m1"); 36 | c2.op2(); 37 | } 38 | 39 | public void m2() { 40 | System.out.println("Mediator m2"); 41 | c1.op1(); 42 | } 43 | 44 | // Mediator 必須識得每一個 Colleague 45 | public void registerColleague1(Colleague1 c) { 46 | this.c1 = c; 47 | } 48 | 49 | public void registerColleague2(Colleague2 c) { 50 | this.c2 = c; 51 | } 52 | 53 | } 54 | 55 | abstract class Colleague { 56 | protected IMediator med; 57 | 58 | public Colleague(IMediator med) { 59 | this.med = med; 60 | } 61 | } 62 | 63 | class Colleague1 extends Colleague { 64 | public Colleague1(IMediator med) { 65 | super(med); 66 | med.registerColleague1(this); 67 | } 68 | 69 | void m1() { 70 | System.out.println("Colleague1.m1"); 71 | med.m1(); 72 | } 73 | 74 | void op1() { 75 | System.out.println("Colleague1.op1"); 76 | } 77 | } 78 | 79 | class Colleague2 extends Colleague { 80 | public Colleague2(IMediator med) { 81 | super(med); 82 | med.registerColleague2(this); 83 | } 84 | 85 | void m2() { 86 | System.out.println("Colleague2.m2"); 87 | med.m2(); 88 | } 89 | 90 | void op2() { 91 | System.out.println("Colleague2.op2"); 92 | } 93 | } 94 | -------------------------------------------------------------------------------- /src/observer/delegation/ObserverDelegationDemo.java: -------------------------------------------------------------------------------- 1 | package observer.delegation; 2 | 3 | import java.util.Observer; 4 | import java.util.Observable; 5 | 6 | public class ObserverDelegationDemo { 7 | 8 | public static void main(String[] args) { 9 | // Note I did not "addObserver()" in the first increase() 10 | Stock s = new Stock(100); 11 | s.increase(); 12 | 13 | s.addObserver(new StockBoard()); 14 | s.increase(); 15 | 16 | s.addObserver(new StockPicView()); 17 | s.increase(); 18 | 19 | } 20 | 21 | } 22 | 23 | class Something {} 24 | 25 | /* 26 | * Stock inherits Something, so it can't inherit Observable directly. 27 | */ 28 | class Stock extends Something { 29 | int price; 30 | DelegatedObservable observable; 31 | 32 | public Stock(int price) { 33 | this.price = price; 34 | observable = new DelegatedObservable(); 35 | } 36 | 37 | public void increase() { 38 | price++; 39 | observable.setChanged(); 40 | observable.notifyObservers(new Integer(price)); 41 | } 42 | 43 | public void addObserver(Observer obs) { 44 | observable.addObserver(obs); 45 | } 46 | } 47 | 48 | /* 49 | * Since the methods "clearChanged()" and "setChanged()" is declared as protected, 50 | * not public, therefore the Stock class can't call directly. 51 | * This class just "open" the interface from "protected" to "public" 52 | */ 53 | class DelegatedObservable extends Observable { 54 | public void clearChanged() { 55 | super.clearChanged(); 56 | } 57 | 58 | public void setChanged() { 59 | super.setChanged(); 60 | } 61 | } 62 | 63 | class StockBoard implements Observer { 64 | public void update(Observable observable, Object value) { 65 | System.out.println("The value is changed to "+ ((Integer)value).intValue()); 66 | } 67 | } 68 | 69 | class StockPicView implements Observer { 70 | public void update(Observable observable, Object value) { 71 | System.out.println("Hi, I am StrockPicView, the value is changed to "+ ((Integer)value).intValue()); 72 | } 73 | 74 | } -------------------------------------------------------------------------------- /src/basic/javaclass/PeopleDemo.java: -------------------------------------------------------------------------------- 1 | package basic.javaclass; 2 | import java.util.*; 3 | 4 | public class PeopleDemo { 5 | 6 | public static void main(String[] args) { 7 | 8 | People p1 = new People("john Lin"); 9 | System.out.println("People created:" + People.count); 10 | People p2 = new People("mary Lee"); 11 | People p3 = new People("tin Chen"); 12 | 13 | System.out.println("People created:" + People.count); 14 | 15 | System.out.println("Pepple: john Lin"); 16 | String firstName = People.getFirstName("john Lin"); 17 | System.out.println("first name: " + firstName); 18 | 19 | String lastName = People.getLastName("john Lin"); 20 | System.out.println("first name: " + lastName); 21 | } 22 | 23 | } 24 | 25 | class People { 26 | private String pName; 27 | private String pTel; 28 | private String status; 29 | public static int count=0; 30 | 31 | public static String getFirstName(String name) { 32 | String firstName=""; 33 | StringTokenizer st = new StringTokenizer(name); 34 | firstName = st.nextToken(); 35 | return firstName; 36 | } 37 | 38 | public static String getLastName(String name) { 39 | String lastName=""; 40 | StringTokenizer st = new StringTokenizer(name); 41 | while (st.hasMoreTokens()) { 42 | lastName = st.nextToken(); 43 | } 44 | return lastName; } 45 | 46 | 47 | public People(String name) { 48 | count++; 49 | pName = name; 50 | sleep(); 51 | } 52 | 53 | public String getpTel() { 54 | return pTel; 55 | } 56 | public void setpTel(String pTel) { 57 | this.pTel = pTel; 58 | } 59 | public String getpName() { 60 | return pName; 61 | } 62 | 63 | public void print() { 64 | System.out.println(pName + ", tel is " + pTel + ". He is "+ status); 65 | } 66 | 67 | public void work() { 68 | status = "working..."; 69 | } 70 | 71 | public void sleep() { 72 | status = "sleep..."; 73 | } 74 | 75 | public void call () { 76 | if (pTel != null) { 77 | status = "calling..."; 78 | } 79 | } 80 | 81 | } 82 | -------------------------------------------------------------------------------- /src/abstractfactory/AbstractFactory.java: -------------------------------------------------------------------------------- 1 | public class Main { 2 | public static void main(String args[]) { 3 | Client c = new Client(); 4 | // 由主程式決定系列 5 | Factory1 cf1 = new Factory1(); 6 | c.doSomeThing(cf1); 7 | } 8 | } 9 | 10 | // Client 只會看到 Abstract 的工廠和零件 11 | class Client { 12 | // 不同的工廠,產生不同系列的零件 13 | void doSomeThing(AbstractFacotry f) { 14 | AbstractProductA a = f.createProductA(); 15 | AbstractProductB b = f.createProductB(); 16 | ... 17 | } 18 | } 19 | 20 | //抽象零件 A,定義零件 A 的規格(方法) 21 | abstract class AbstractProductA { 22 | //零件 A 需要履行的功能 23 | public abstract void m1(int x); 24 | } 25 | 26 | //系列1 的零件 A 27 | class ProductA1 extends AbstractProductA { 28 | public abstract void m1(int x) { 29 | ... // 系列1 的實踐的方法 30 | } 31 | } 32 | //系列2 的零件 A 33 | class ProductA2 extends AbstractProductA { 34 | public abstract void m1(int x) { 35 | ... // 系列2 的實踐的方法 36 | } 37 | } 38 | 39 | //抽象零件 B,定義零件 B 的規格(方法) 40 | abstract class AbstractProductB { 41 | //零件 B 需要履行的功能 42 | public abstract void doit(int x); 43 | } 44 | 45 | //系列一的零件 B 46 | class ProductA1 extends AbstractProductA { 47 | public abstract void doit(int x) { 48 | ... // 系列一的實踐的方法 49 | } 50 | } 51 | //系列二的零件 B 52 | class ProductA2 extends AbstractProductA { 53 | public abstract void doit(int x) { 54 | ... // 系列二的實踐的方法 55 | } 56 | } 57 | 58 | // 定義一個工廠所需要產生的產品 59 | interface AbstractFactory { 60 | public AbstractProductA createProductA(); 61 | public AbstractProductB createProductB(); 62 | } 63 | 64 | // 系列一的工廠 65 | class Factory1 implements AbstractFactory { 66 | AbstractProductA createProductA() { 67 | return new ProductA1(); 68 | } 69 | AbstractProductB createProductB() { 70 | return new ProductB1(); 71 | } 72 | } 73 | 74 | // 系列二的工廠 75 | class Factory2 implements AbstractFactory { 76 | AbstractProductA createProductA() { 77 | return new ProductA2(); 78 | } 79 | AbstractProductB createProductB() { 80 | return new ProductB2(); 81 | } 82 | } -------------------------------------------------------------------------------- /src/mvc/noobserver/NoObserverDemo.java: -------------------------------------------------------------------------------- 1 | package mvc.noobserver; 2 | 3 | import java.awt.TextField; 4 | import java.awt.event.ActionEvent; 5 | import java.awt.event.ActionListener; 6 | import java.util.Observable; 7 | import java.util.Observer; 8 | import javax.swing.JButton; 9 | import javax.swing.JFrame; 10 | 11 | /* MODEL */ 12 | class Counter { 13 | int counter = 0; 14 | 15 | public void incCounter() { 16 | counter++; 17 | } 18 | 19 | public int getCounter() { 20 | return counter; 21 | } 22 | } 23 | 24 | /* VIEW */ 25 | class CounterView extends JFrame { 26 | static int id = 0; //just for setting location 27 | private TextField tf = new TextField(10); 28 | 29 | public CounterView(String title) { 30 | super(title); 31 | tf.setText("0"); 32 | add(tf); 33 | this.setSize(200, 100); 34 | this.setLocation(100 + (id++) * 200, 100); 35 | this.setDefaultCloseOperation(EXIT_ON_CLOSE); 36 | } 37 | 38 | public void update(int v) { 39 | tf.setText(String.valueOf(v)); 40 | } 41 | } 42 | 43 | /* CONTROLLER */ 44 | class CounterController extends JFrame implements ActionListener { 45 | static int id = 0; //just for setting location 46 | private JButton inc = new JButton("INC"); 47 | Counter c; 48 | CounterView v; 49 | 50 | public CounterController(Counter c, CounterView v) { 51 | this.c = c; 52 | inc.addActionListener(this); 53 | this.v = v; 54 | add(inc); 55 | this.setTitle("Controller " + id); 56 | this.setSize(200, 100); 57 | this.setLocation(100 + (id++) * 200, 200); 58 | this.setDefaultCloseOperation(EXIT_ON_CLOSE); 59 | } 60 | 61 | public void actionPerformed(ActionEvent arg0) { 62 | c.incCounter(); 63 | v.update(c.getCounter()); 64 | } 65 | } 66 | 67 | public class NoObserverDemo { 68 | 69 | public static void main(String[] args) { 70 | Counter c = new Counter(); 71 | 72 | CounterView view1 = new CounterView("View0"); 73 | view1.setVisible(true); 74 | CounterView view2 = new CounterView("View1"); 75 | view2.setVisible(true); 76 | 77 | CounterController controller1 = new CounterController(c,view1); 78 | controller1.setVisible(true); 79 | CounterController controller2 = new CounterController(c,view2); 80 | controller2.setVisible(true); 81 | } 82 | } -------------------------------------------------------------------------------- /src/mvc/SwingDemo.java: -------------------------------------------------------------------------------- 1 | package mvc; 2 | 3 | import java.awt.TextField; 4 | import java.awt.event.ActionEvent; 5 | import java.awt.event.ActionListener; 6 | import java.util.Observable; 7 | import java.util.Observer; 8 | import javax.swing.JButton; 9 | import javax.swing.JFrame; 10 | 11 | /* MODEL */ 12 | class Counter extends Observable { 13 | int counter = 0; 14 | 15 | public void incCounter() { 16 | counter++; 17 | setChanged(); 18 | notifyObservers(new Integer(counter)); 19 | } 20 | 21 | public int getCounter() { 22 | return counter; 23 | } 24 | } 25 | 26 | /* VIEW */ 27 | class CounterView extends JFrame implements Observer { 28 | static int id = 0; //just for setting location 29 | private TextField tf = new TextField(10); 30 | 31 | public CounterView(String title) { 32 | super(title); 33 | tf.setText("0"); 34 | add(tf); 35 | this.setSize(200, 100); 36 | this.setLocation(100 + (id++) * 200, 100); 37 | this.setDefaultCloseOperation(EXIT_ON_CLOSE); 38 | } 39 | 40 | public void update(Observable arg0, Object arg1) { 41 | int c = ((Integer) arg1).intValue(); 42 | tf.setText(String.valueOf(c)); 43 | } 44 | } 45 | 46 | /* CONTROLLER */ 47 | class CounterController extends JFrame implements ActionListener { 48 | static int id = 0; //just for setting location 49 | private JButton inc = new JButton("INC"); 50 | Counter c; 51 | 52 | public CounterController(Counter c) { 53 | this.c = c; 54 | inc.addActionListener(this); 55 | 56 | add(inc); 57 | this.setTitle("Controller " + id); 58 | this.setSize(200, 100); 59 | this.setLocation(100 + (id++) * 200, 200); 60 | this.setDefaultCloseOperation(EXIT_ON_CLOSE); 61 | } 62 | 63 | public void actionPerformed(ActionEvent arg0) { 64 | c.incCounter(); 65 | } 66 | } 67 | 68 | public class MVCByObserver { 69 | public static void main(String[] args) { 70 | Counter c = new Counter(); 71 | CounterView view1 = new CounterView("View0"); 72 | view1.setVisible(true); 73 | CounterView view2 = new CounterView("View1"); 74 | view2.setVisible(true); 75 | c.addObserver(view1); //add view 76 | c.addObserver(view2); //add view 77 | CounterController controller1 = new CounterController(c); 78 | controller1.setVisible(true); 79 | CounterController controller2 = new CounterController(c); 80 | controller2.setVisible(true); 81 | } 82 | } -------------------------------------------------------------------------------- /src/mvc/MVCByObserver.java: -------------------------------------------------------------------------------- 1 | package mvc; 2 | 3 | import java.awt.TextField; 4 | import java.awt.event.ActionEvent; 5 | import java.awt.event.ActionListener; 6 | import java.util.Observable; 7 | import java.util.Observer; 8 | import javax.swing.JButton; 9 | import javax.swing.JFrame; 10 | 11 | /* MODEL */ 12 | class Counter extends Observable { 13 | int counter = 0; 14 | 15 | public void incCounter() { 16 | counter++; 17 | setChanged(); 18 | notifyObservers(new Integer(counter)); 19 | } 20 | 21 | public int getCounter() { 22 | return counter; 23 | } 24 | } 25 | 26 | /* VIEW */ 27 | class CounterView extends JFrame implements Observer { 28 | static int id = 0; //just for setting location 29 | private TextField tf = new TextField(10); 30 | 31 | public CounterView(String title) { 32 | super(title); 33 | tf.setText("0"); 34 | add(tf); 35 | this.setSize(200, 100); 36 | this.setLocation(100 + (id++) * 200, 100); 37 | this.setDefaultCloseOperation(EXIT_ON_CLOSE); 38 | } 39 | 40 | public void update(Observable arg0, Object arg1) { 41 | int c = ((Integer) arg1).intValue(); 42 | tf.setText(String.valueOf(c)); 43 | } 44 | } 45 | 46 | /* CONTROLLER */ 47 | class CounterController extends JFrame implements ActionListener { 48 | static int id = 0; //just for setting location 49 | private JButton inc = new JButton("INC"); 50 | Counter c; 51 | 52 | public CounterController(Counter c) { 53 | this.c = c; 54 | inc.addActionListener(this); 55 | 56 | add(inc); 57 | this.setTitle("Controller " + id); 58 | this.setSize(200, 100); 59 | this.setLocation(100 + (id++) * 200, 200); 60 | this.setDefaultCloseOperation(EXIT_ON_CLOSE); 61 | } 62 | 63 | public void actionPerformed(ActionEvent arg0) { 64 | c.incCounter(); 65 | } 66 | } 67 | 68 | public class MVCByObserver { 69 | public static void main(String[] args) { 70 | Counter c = new Counter(); 71 | CounterView view1 = new CounterView("View0"); 72 | view1.setVisible(true); 73 | CounterView view2 = new CounterView("View1"); 74 | view2.setVisible(true); 75 | c.addObserver(view1); //add view 76 | c.addObserver(view2); //add view 77 | CounterController controller1 = new CounterController(c); 78 | controller1.setVisible(true); 79 | CounterController controller2 = new CounterController(c); 80 | controller2.setVisible(true); 81 | } 82 | } -------------------------------------------------------------------------------- /src/observer/stock/ObserverStockDemo.java: -------------------------------------------------------------------------------- 1 | package observer.stock; 2 | 3 | import java.awt.GridLayout; 4 | import java.awt.event.ActionEvent; 5 | import java.awt.event.ActionListener; 6 | import java.util.Observable; 7 | import java.util.Random; 8 | import javax.swing.JButton; 9 | import javax.swing.JFrame; 10 | import javax.swing.JLabel; 11 | import javax.swing.JPanel; 12 | import javax.swing.JTextField; 13 | 14 | public class ObserverStockDemo extends JFrame implements ActionListener { 15 | Stock s; 16 | CurrentPriceBoard priceBoard; 17 | 18 | public ObserverStockDemo() { 19 | super(); 20 | 21 | s = new Stock(100); 22 | priceBoard = new CurrentPriceBoard(); 23 | s.addObserver(priceBoard); 24 | 25 | this.setLayout(new GridLayout(2, 2)); 26 | add(this.priceBoard); 27 | JButton startBtn = new JButton("Change"); 28 | startBtn.addActionListener(this); 29 | add(startBtn); 30 | setSize(300, 200); 31 | setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 32 | } 33 | 34 | public void actionPerformed(ActionEvent e) { 35 | Random r = new Random(); 36 | double diff = (r.nextDouble() * 0.07); 37 | boolean positive = r.nextBoolean(); 38 | double newPrice; 39 | if (positive) 40 | newPrice = s.getPrice() * (1.0 + diff); 41 | else 42 | newPrice = s.getPrice() * (1.0 - diff); 43 | s.setPrice(Math.round(newPrice)); 44 | } 45 | 46 | public static void main(String[] args) { 47 | ObserverStockDemo demo = new ObserverStockDemo(); 48 | demo.setVisible(true); 49 | } 50 | 51 | } 52 | 53 | class Stock extends java.util.Observable { 54 | double yesdayPrice; 55 | double currentPrice; 56 | int currentAmount; 57 | 58 | public Stock(int yesterday) { 59 | this.yesdayPrice = yesterday; 60 | this.currentPrice = this.yesdayPrice; 61 | this.setChanged(); 62 | this.notifyObservers(); 63 | } 64 | 65 | void setPrice(double p) { 66 | this.currentPrice = p; 67 | this.setChanged(); 68 | this.notifyObservers(); 69 | } 70 | 71 | double getPrice() { 72 | return this.currentPrice; 73 | } 74 | 75 | void setAmount(int a) { 76 | this.currentAmount = a; 77 | this.setChanged(); 78 | this.notifyObservers(); 79 | } 80 | } 81 | 82 | class CurrentPriceBoard extends JPanel implements java.util.Observer { 83 | JTextField price = new JTextField(10); 84 | 85 | public CurrentPriceBoard() { 86 | super(); 87 | add(new JLabel("Current price")); 88 | add(price); 89 | } 90 | 91 | public void update(Observable arg0, Object arg1) { 92 | double p = ((Stock) arg0).getPrice(); 93 | price.setText(Double.toString(p)); 94 | } 95 | } -------------------------------------------------------------------------------- /src/chess/chessv1/ChessGameV1.java: -------------------------------------------------------------------------------- 1 | package chess.chessv1; 2 | 3 | public class ChessGameV1 { 4 | public static final int BLACK = 0, RED = 1; 5 | Chess[] black; 6 | Chess[] red; 7 | 8 | public static void main(String args[]) { 9 | // initialize the game 10 | ChessGameV1 game = new ChessGameV1(); 11 | game.generateChess(); 12 | game.showAllChess(); 13 | } 14 | 15 | void showAllChess() { 16 | for (Chess c : black) { 17 | System.out.println(c); 18 | } 19 | for (Chess c : red) { 20 | System.out.println(c); 21 | } 22 | } 23 | 24 | void generateChess() { 25 | black = new Chess[] { new Chess("將", 1, BLACK, 0), 26 | new Chess("士", 2, BLACK, 1), 27 | new Chess("士", 2, BLACK, 2), 28 | new Chess("象", 3, BLACK, 3), 29 | new Chess("象", 3, BLACK, 4), 30 | new Chess("車", 3, BLACK, 5), 31 | new Chess("車", 3, BLACK, 6), 32 | new Chess("馬", 3, BLACK, 7), 33 | new Chess("馬", 3, BLACK, 8), 34 | new Chess("包", 3, BLACK, 9), 35 | new Chess("包", 3, BLACK, 10), 36 | new Chess("卒", 3, BLACK, 11), 37 | new Chess("卒", 3, BLACK, 12), 38 | new Chess("卒", 3, BLACK, 13), 39 | new Chess("卒", 3, BLACK, 14), 40 | new Chess("卒", 3, BLACK, 15), }; 41 | 42 | red = new Chess[] { new Chess("帥", 1, RED, 16), 43 | new Chess("仕", 2, RED, 17), 44 | new Chess("仕", 2, RED, 18), 45 | new Chess("相", 3, RED, 19), 46 | new Chess("相", 3, BLACK, 20), 47 | new Chess("俥", 3, BLACK, 21), 48 | new Chess("俥", 3, BLACK, 22), 49 | new Chess("傌", 3, BLACK, 23), 50 | new Chess("傌", 3, BLACK, 24), 51 | new Chess("炮", 3, BLACK, 25), 52 | new Chess("炮", 3, BLACK, 26), 53 | new Chess("兵", 3, BLACK, 27), 54 | new Chess("兵", 3, BLACK, 28), 55 | new Chess("兵", 3, BLACK, 29), 56 | new Chess("兵", 3, BLACK, 30), 57 | new Chess("兵", 3, BLACK, 31), }; 58 | 59 | // change black's location 60 | for (int i = 0; i < 16; i++) { 61 | int target = (int) (Math.random() * 32); 62 | if (target < 16) { 63 | int originalLoc = black[i].loc; 64 | black[i].loc = target; 65 | black[target].loc = originalLoc; 66 | } else if (target < 32) { 67 | target -= 16; 68 | int originalLoc = black[i].loc; 69 | black[i].loc = target; 70 | red[target].loc = originalLoc; 71 | } else { 72 | System.out.println("Location Error"); 73 | } 74 | } 75 | 76 | } 77 | } 78 | 79 | class Chess { 80 | public Chess(String name, int weight, int side, int loc) { 81 | this.name = name; 82 | this.weight = weight; 83 | this.side = side; 84 | this.loc = loc; 85 | } 86 | 87 | String name; 88 | int weight; 89 | int side; 90 | int loc; 91 | 92 | public String toString() { 93 | return name + ", " + weight + ", loc=" + loc; 94 | } 95 | 96 | } -------------------------------------------------------------------------------- /src/basic/javainheritance/DiscountSaleDemo.java: -------------------------------------------------------------------------------- 1 | package basic.javainheritance; 2 | 3 | /** 4 | Class for a sale of one item with discount expressed as a percent of the price, 5 | but no other adjustments. 6 | Class invariant: The price is always nonnegative; the name is a 7 | nonempty string; the discount is always nonnegative. 8 | */ 9 | 10 | class DiscountSale extends Sale 11 | { 12 | private double discount; //A percent of the price. Cannot be negative. 13 | 14 | public DiscountSale( ) 15 | { 16 | super( ); 17 | discount = 0; 18 | } 19 | 20 | /** 21 | Precondition: theName is a nonempty string; thePrice is nonnegative; 22 | theDiscount is expressed as a percent of the price and is nonnegative. 23 | */ 24 | public DiscountSale(String theName, 25 | double thePrice, double theDiscount) 26 | { 27 | super(theName, thePrice); 28 | setDiscount(theDiscount); 29 | } 30 | 31 | public DiscountSale(DiscountSale originalObject) 32 | { 33 | super(originalObject); 34 | discount = originalObject.discount; 35 | } 36 | 37 | public static void announcement( ) 38 | { 39 | System.out.println("This is the DiscountSale class."); 40 | } 41 | 42 | public double bill( ) 43 | { 44 | double fraction = discount/100; 45 | return (1 - fraction)*getPrice( ); 46 | } 47 | 48 | public double getDiscount( ) 49 | { 50 | return discount; 51 | } 52 | 53 | /** 54 | Precondition: Discount is nonnegative. 55 | */ 56 | public void setDiscount(double newDiscount) 57 | { 58 | if (newDiscount >= 0) 59 | discount = newDiscount; 60 | else 61 | { 62 | System.out.println("Error: Negative discount."); 63 | System.exit(0); 64 | } 65 | } 66 | 67 | public String toString( ) 68 | { 69 | return (getName( ) + " Price = $" + getPrice( ) 70 | + " Discount = " + discount + "%\n" 71 | + " Total cost = $" + bill( )); 72 | } 73 | 74 | public boolean equals(Object otherObject) 75 | { 76 | if (otherObject == null) 77 | return false; 78 | else if (getClass( ) != otherObject.getClass( )) 79 | return false; 80 | else 81 | { 82 | DiscountSale otherDiscountSale = 83 | (DiscountSale)otherObject; 84 | return (super.equals(otherDiscountSale) 85 | && discount == otherDiscountSale.discount); 86 | } 87 | } 88 | 89 | public DiscountSale clone( ) 90 | { 91 | return new DiscountSale(this ); 92 | } 93 | } 94 | 95 | public class DiscountSaleDemo { 96 | 97 | } 98 | 99 | -------------------------------------------------------------------------------- /src/uml/GradeBookApp2a.java: -------------------------------------------------------------------------------- 1 | /* 2 | FIX the bug in GradeBookApp2 3 | * In a double navigation, Teacher set reference to Course, 4 | and Course set reference to Teacher 5 | */ 6 | 7 | public class GradeBookApp2a { 8 | public static void main(String args[]) { 9 | Student Jie = new Student ("Jie"); 10 | Student Albert = new Student ("Albert"); 11 | 12 | Teacher Nick = new Teacher ("Nick"); 13 | 14 | Course Java = new Course ("Java", 3); 15 | Course Python = new Course ("Python", 3); 16 | 17 | Nick.offer(Java); 18 | Nick.offer(Python); 19 | 20 | Jie.takeCourse(Java); 21 | Albert.takeCourse(Java); 22 | 23 | Java.showCourseInfo(); 24 | } 25 | } 26 | 27 | class Course { 28 | String cName; 29 | private int degree; 30 | Student[] students = new Student[10]; 31 | int studentCount = 0; 32 | Teacher teacher = new Teacher("None"); 33 | public Course (String name, int degree) { 34 | this.cName = name; 35 | this.degree = degree; 36 | } 37 | 38 | public void registeredBy(Student s) { 39 | if (studentCount <= 9) 40 | students[studentCount++] = s; 41 | else 42 | System.out.println("Students overflow in a class"); 43 | } 44 | 45 | public void showCourseInfo() { 46 | System.out.println("Course: "+ cName); 47 | System.out.println("-- Teacher: " + teacher.tName); 48 | String s = ""; 49 | for (int i=0; i= 0) 56 | price = newPrice; 57 | else 58 | { 59 | System.out.println("Error: Negative price."); 60 | System.exit(0); 61 | } 62 | } 63 | 64 | public String getName( ) 65 | { 66 | return name; 67 | } 68 | 69 | /** 70 | Precondition: newName is a nonempty string. 71 | */ 72 | public void setName(String newName) 73 | { 74 | if (newName != null && newName != "") 75 | name = newName; 76 | else 77 | { 78 | System.out.println("Error: Improper name value."); 79 | System.exit(0); 80 | } 81 | } 82 | 83 | public String toString( ) 84 | { 85 | return (name + " Price and total cost = $" + price); 86 | } 87 | 88 | public double bill( ) 89 | { 90 | return price; 91 | } 92 | 93 | /* 94 | Returns true if the names are the same and the bill for the calling 95 | object is equal to the bill for otherSale; otherwise returns false. 96 | Also returns false if otherObject is null. 97 | */ 98 | public boolean equalDeals(Sale otherSale) 99 | { 100 | if (otherSale == null) 101 | return false; 102 | else 103 | return (name.equals(otherSale.name) 104 | && bill( ) == otherSale.bill( )); 105 | } 106 | 107 | /* 108 | Returns true if the bill for the calling object is less 109 | than the bill for otherSale; otherwise returns false. 110 | */ 111 | public boolean lessThan (Sale otherSale) 112 | { 113 | if (otherSale == null) 114 | { 115 | System.out.println("Error: null Sale object."); 116 | System.exit(0); 117 | } 118 | //else 119 | return (bill( ) < otherSale.bill( )); 120 | } 121 | 122 | public boolean equals(Object otherObject) 123 | { 124 | if (otherObject == null) 125 | return false; 126 | else if (getClass( ) != otherObject.getClass( )) 127 | return false; 128 | else 129 | { 130 | Sale otherSale = (Sale)otherObject; 131 | return (name.equals(otherSale.name) 132 | && (price == otherSale.price)); 133 | } 134 | } 135 | 136 | public Sale clone( ) 137 | { 138 | return new Sale(this ); 139 | } 140 | } 141 | 142 | -------------------------------------------------------------------------------- /src/mediator/BookStoreDemo.java: -------------------------------------------------------------------------------- 1 | package mediator; 2 | 3 | import java.awt.Font; 4 | import java.awt.event.ActionEvent; 5 | import java.awt.event.ActionListener; 6 | 7 | import javax.swing.JButton; 8 | import javax.swing.JFrame; 9 | import javax.swing.JLabel; 10 | import javax.swing.JPanel; 11 | 12 | public class BookStoreDemo extends JFrame implements ActionListener { 13 | IMediator med = new BookStoreMediator(); 14 | 15 | BookStoreDemo() { 16 | JPanel p = new JPanel(); 17 | p.add(new BtnView(this, med)); 18 | p.add(new BtnBook(this, med)); 19 | p.add(new BtnSearch(this, med)); 20 | getContentPane().add(new LblDisplay(med), "North"); 21 | getContentPane().add(p, "South"); 22 | setSize(300, 100); 23 | setVisible(true); 24 | setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 25 | } 26 | 27 | // 所有的 Colleague 都有統一的介面:Command 28 | public void actionPerformed(ActionEvent ae) { 29 | Command comd = (Command) ae.getSource(); 30 | comd.execute(); 31 | } 32 | 33 | public static void main(String[] args) { 34 | new BookStoreDemo(); 35 | } 36 | } 37 | 38 | // Colleague interface 39 | interface Command { 40 | void execute(); 41 | } 42 | 43 | // Abstract Mediator, 定義所有 Mediator 的規格 44 | interface IMediator { 45 | public void book(); 46 | 47 | public void view(); 48 | 49 | public void search(); 50 | 51 | public void registerView(BtnView v); 52 | 53 | public void registerSearch(BtnSearch s); 54 | 55 | public void registerBook(BtnBook b); 56 | 57 | public void registerDisplay(LblDisplay d); 58 | } 59 | 60 | // Concrete mediator 61 | class BookStoreMediator implements IMediator { 62 | 63 | BtnView btnView; 64 | BtnSearch btnSearch; 65 | BtnBook btnBook; 66 | LblDisplay show; 67 | 68 | // 註冊後 mediator 才知道 BtnView 69 | public void registerView(BtnView v) { 70 | btnView = v; 71 | } 72 | 73 | public void registerSearch(BtnSearch s) { 74 | btnSearch = s; 75 | } 76 | 77 | public void registerBook(BtnBook b) { 78 | btnBook = b; 79 | } 80 | 81 | public void registerDisplay(LblDisplay d) { 82 | show = d; 83 | } 84 | 85 | // book 時所有需要溝通設定的都在這裡進行 86 | public void book() { 87 | btnBook.setEnabled(false); 88 | btnView.setEnabled(true); 89 | btnSearch.setEnabled(true); 90 | show.setText("Booking..."); 91 | } 92 | 93 | // view 時所有需要溝通設定的都在這裡進行 94 | public void view() { 95 | btnView.setEnabled(false); 96 | btnSearch.setEnabled(true); 97 | btnBook.setEnabled(true); 98 | show.setText("Viewing..."); 99 | } 100 | 101 | // search 時所有需要溝通設定的都在這裡進行 102 | public void search() { 103 | btnSearch.setEnabled(false); 104 | btnView.setEnabled(true); 105 | btnBook.setEnabled(true); 106 | show.setText("Searching..."); 107 | } 108 | } 109 | 110 | // A concrete colleague 111 | class BtnView extends JButton implements Command { 112 | IMediator med; 113 | 114 | // colleague 也需要知道 mediator 115 | BtnView(ActionListener al, IMediator m) { 116 | super("View"); 117 | addActionListener(al); 118 | med = m; 119 | med.registerView(this); 120 | } 121 | 122 | // 轉呼叫 medicator 來處理 123 | public void execute() { 124 | med.view(); 125 | } 126 | } 127 | 128 | // A concrete colleague 129 | class BtnSearch extends JButton implements Command { 130 | IMediator med; 131 | 132 | BtnSearch(ActionListener al, IMediator m) { 133 | super("Search"); 134 | addActionListener(al); 135 | med = m; 136 | med.registerSearch(this); 137 | } 138 | 139 | public void execute() { 140 | med.search(); 141 | } 142 | 143 | } 144 | 145 | // A concrete colleague 146 | class BtnBook extends JButton implements Command { 147 | IMediator med; 148 | 149 | BtnBook(ActionListener al, IMediator m) { 150 | super("Book"); 151 | addActionListener(al); 152 | med = m; 153 | med.registerBook(this); 154 | } 155 | 156 | public void execute() { 157 | med.book(); 158 | } 159 | 160 | } 161 | 162 | class LblDisplay extends JLabel { 163 | IMediator med; 164 | 165 | LblDisplay(IMediator m) { 166 | super("Just start..."); 167 | med = m; 168 | med.registerDisplay(this); 169 | setFont(new Font("Arial", Font.BOLD, 24)); 170 | } 171 | } 172 | -------------------------------------------------------------------------------- /src/basic/javainheritance/ComparableDemo.java: -------------------------------------------------------------------------------- 1 | package basic.javainheritance; 2 | 3 | /** 4 | * Demonstrates sorting arrays for classes that implement the Comparable 5 | * interface. 6 | */ 7 | public class ComparableDemo { 8 | public static void main(String[] args) { 9 | 10 | // ===== Sort Double 11 | Double[] d = new Double[10]; 12 | for (int i = 0; i < d.length; i++) 13 | d[i] = new Double(d.length - i); 14 | 15 | System.out.println("Before sorting:"); 16 | int i; 17 | for (i = 0; i < d.length; i++) 18 | System.out.print(d[i].doubleValue() + ", "); 19 | System.out.println(); 20 | 21 | GeneralizedSelectionSort.sort(d, d.length); 22 | 23 | System.out.println("After sorting:"); 24 | for (i = 0; i < d.length; i++) 25 | System.out.print(d[i].doubleValue() + ", "); 26 | System.out.println(); 27 | 28 | // ===== Sort String[] 29 | String[] a = new String[10]; 30 | a[0] = "dog"; 31 | a[1] = "cat"; 32 | a[2] = "cornish game hen"; 33 | int numberUsed = 3; 34 | 35 | System.out.println("Before sorting:"); 36 | for (i = 0; i < numberUsed; i++) 37 | System.out.print(a[i] + ", "); 38 | System.out.println(); 39 | 40 | GeneralizedSelectionSort.sort(a, numberUsed); 41 | 42 | System.out.println("After sorting:"); 43 | for (i = 0; i < numberUsed; i++) 44 | System.out.print(a[i] + ", "); 45 | System.out.println(); 46 | 47 | // ===== Sort People 48 | People[] p = new People[10]; 49 | p[0] = new People("J", 12); 50 | p[1] = new People("M", 99); 51 | p[2] = new People("K", 43); 52 | numberUsed = 3; 53 | 54 | System.out.println("Before sorting:"); 55 | for (i = 0; i < numberUsed; i++) 56 | System.out.print(p[i] + ", "); 57 | System.out.println(); 58 | 59 | GeneralizedSelectionSort.sort(p, numberUsed); 60 | 61 | System.out.println("After sorting:"); 62 | for (i = 0; i < numberUsed; i++) 63 | System.out.print(p[i] + ", "); 64 | System.out.println(); 65 | 66 | } 67 | } 68 | 69 | //interface Comparable { 70 | // int compareTo(Object obj); 71 | //} 72 | 73 | class GeneralizedSelectionSort { 74 | /** 75 | * Precondition: numberUsed <= a.length; The first numberUsed indexed 76 | * variables have values. Action: Sorts a so that a[0, a[1], ... , 77 | * a[numberUsed - 1] are in increasing order by the compareTo method. 78 | */ 79 | public static void sort(Comparable[] a, int numberUsed) { 80 | int index, indexOfNextSmallest; 81 | for (index = 0; index < numberUsed - 1; index++) {// Place the correct 82 | // value in 83 | // a[index]: 84 | indexOfNextSmallest = indexOfSmallest(index, a, numberUsed); 85 | interchange(index, indexOfNextSmallest, a); 86 | // a[0], a[1],..., a[index] are correctly ordered and these are 87 | // the smallest of the original array elements. The remaining 88 | // positions contain the rest of the original array elements. 89 | } 90 | } 91 | 92 | /** 93 | * Returns the index of the smallest value among a[startIndex], 94 | * a[startIndex+1], ... a[numberUsed - 1] 95 | */ 96 | private static int indexOfSmallest(int startIndex, Comparable[] a, 97 | int numberUsed) { 98 | Comparable min = a[startIndex]; 99 | int indexOfMin = startIndex; 100 | int index; 101 | for (index = startIndex + 1; index < numberUsed; index++) 102 | if (a[index].compareTo(min) < 0)// if a[index] is less than min 103 | { 104 | min = a[index]; 105 | indexOfMin = index; 106 | // min is smallest of a[startIndex] through a[index] 107 | } 108 | return indexOfMin; 109 | } 110 | 111 | /** 112 | * Precondition: i and j are legal indices for the array a. Postcondition: 113 | * Values of a[i] and a[j] have been interchanged. 114 | */ 115 | private static void interchange(int i, int j, Comparable[] a) { 116 | Comparable temp; 117 | temp = a[i]; 118 | a[i] = a[j]; 119 | a[j] = temp; // original value of a[i] 120 | } 121 | 122 | } 123 | 124 | class People implements Comparable { 125 | 126 | int age; 127 | String name; 128 | 129 | public People(String n, int age) { 130 | super(); 131 | this.name = n; 132 | this.age = age; 133 | } 134 | 135 | public int compareTo(Object arg0) { 136 | if (age >= ((People) arg0).getAge()) { 137 | return 1; 138 | } else 139 | return -1; 140 | } 141 | 142 | public int getAge() { 143 | return age; 144 | } 145 | 146 | @Override 147 | public String toString() { 148 | return name; 149 | } 150 | 151 | } 152 | -------------------------------------------------------------------------------- /src/chess/chessv2/ChessGameV2.java: -------------------------------------------------------------------------------- 1 | package chess.chessv2; 2 | 3 | /* 4 | * Force every chess game to have two players 5 | */ 6 | abstract class AbstractGame { 7 | abstract void setPlayers(Player p1, Player p2); 8 | } 9 | 10 | /* 11 | * Version 2 chess game 12 | */ 13 | public class ChessGameV2 extends AbstractGame { 14 | public static final int BLACK = 0, RED = 1; 15 | Chess[] black; 16 | Chess[] red; 17 | Player p1, p2; 18 | 19 | public static void main(String args[]) { 20 | // initialize the game 21 | ChessGameV2 game = new ChessGameV2(); 22 | game.setPlayers(new Player("Mary"), new Player("Jack")); 23 | game.generateChess(); 24 | game.showAllChess(); 25 | } 26 | 27 | /** 28 | * Set all (32 chess), including their name, weight, location. 29 | */ 30 | void generateChess() { 31 | black = new Chess[] { new Chess("將", 1, BLACK, 0), 32 | new Chess("士", 2, BLACK, 1), 33 | new Chess("士", 2, BLACK, 2), 34 | new Chess("象", 3, BLACK, 3), 35 | new Chess("象", 3, BLACK, 4), 36 | new Chess("車", 3, BLACK, 5), 37 | new Chess("車", 3, BLACK, 6), 38 | new Chess("馬", 3, BLACK, 7), 39 | new Chess("馬", 3, BLACK, 8), 40 | new Chess("包", 3, BLACK, 9), 41 | new Chess("包", 3, BLACK, 10), 42 | new Chess("卒", 3, BLACK, 11), 43 | new Chess("卒", 3, BLACK, 12), 44 | new Chess("卒", 3, BLACK, 13), 45 | new Chess("卒", 3, BLACK, 14), 46 | new Chess("卒", 3, BLACK, 15), }; 47 | 48 | red = new Chess[] { new Chess("帥", 1, RED, 16), 49 | new Chess("仕", 2, RED, 17), 50 | new Chess("仕", 2, RED, 18), 51 | new Chess("相", 3, RED, 19), 52 | new Chess("相", 3, BLACK, 20), 53 | new Chess("俥", 3, BLACK, 21), 54 | new Chess("俥", 3, BLACK, 22), 55 | new Chess("傌", 3, BLACK, 23), 56 | new Chess("傌", 3, BLACK, 24), 57 | new Chess("炮", 3, BLACK, 25), 58 | new Chess("炮", 3, BLACK, 26), 59 | new Chess("兵", 3, BLACK, 27), 60 | new Chess("兵", 3, BLACK, 28), 61 | new Chess("兵", 3, BLACK, 29), 62 | new Chess("兵", 3, BLACK, 30), 63 | new Chess("兵", 3, BLACK, 31), }; 64 | 65 | // change black's location 66 | for (int i = 0; i < 16; i++) { 67 | int target = (int) (Math.random() * 32); 68 | if (target < 16) { 69 | int originalLoc = black[i].loc; 70 | black[i].loc = target; 71 | black[target].loc = originalLoc; 72 | } else if (target < 32) { 73 | target -= 16; 74 | int originalLoc = black[i].loc; 75 | black[i].loc = target; 76 | red[target].loc = originalLoc; 77 | } else { 78 | System.out.println("Location Error"); 79 | } 80 | } 81 | 82 | } 83 | 84 | @Override 85 | void setPlayers(Player p1, Player p2) { 86 | this.p1 = p1; 87 | this.p2 = p2; 88 | } 89 | 90 | /** 91 | * Show all chess in the game 92 | */ 93 | void showAllChess() { 94 | System.out.println("Players: " + p1 + " vs. " + p2); 95 | for (Chess c : black) { 96 | System.out.println(c); 97 | } 98 | for (Chess c : red) { 99 | System.out.println(c); 100 | } 101 | } 102 | 103 | } 104 | 105 | class Chess { 106 | 107 | public Chess(String name, int weight, int side, int loc) { 108 | this.name = name; 109 | this.weight = weight; 110 | this.side = side; 111 | this.loc = loc; 112 | } 113 | 114 | String name; 115 | int weight; 116 | int side; 117 | int loc; 118 | 119 | public String toString() { 120 | return name + ", \t" + weight + ", loc=" + this.getLocation(); 121 | } 122 | 123 | public Location getLocation() { 124 | return Location.getLocation(loc); 125 | } 126 | 127 | public int getLoc() { 128 | return loc; 129 | } 130 | } 131 | 132 | class Player { 133 | String name; 134 | 135 | public Player(String n) { 136 | this.name = n; 137 | } 138 | 139 | public String toString() { 140 | return name; 141 | } 142 | } 143 | 144 | /* 145 | * Location of a chess. It is composed of (x,y) 146 | * x should be in the range (0,7), y: (0, 3) 147 | */ 148 | class Location { 149 | int x, y; 150 | 151 | public Location(int x, int y) { 152 | boolean xOK = (x >= 0 && x <= 7); 153 | boolean yOK = (y >= 0 && y <= 3); 154 | if (!(xOK && yOK)) { 155 | System.out.println("Location Error:" + x + ", " + y); 156 | System.exit(0); 157 | } 158 | this.x = x; 159 | this.y = y; 160 | } 161 | 162 | public String toString() { 163 | return "(" + x + ", " + y + ")"; 164 | } 165 | 166 | public static Location getLocation(int loc) { 167 | int x = (loc / 4); 168 | int y = (loc % 4); 169 | return new Location(x, y); 170 | } 171 | } -------------------------------------------------------------------------------- /src/chess/chessv3/ChessGameV3.java: -------------------------------------------------------------------------------- 1 | package chess.chessv3; 2 | 3 | /* 4 | * Force every chess game to have two players 5 | */ 6 | abstract class AbstractGame { 7 | abstract void setPlayers(Player p1, Player p2); 8 | } 9 | 10 | /* 11 | * Version 3 chess game 12 | */ 13 | public class ChessGameV3 extends AbstractGame { 14 | public static final int BLACK = 0, RED = 1; 15 | Chess[] black; 16 | Chess[] red; 17 | Player p1, p2; 18 | 19 | public static void main(String args[]) { 20 | // initialize the game 21 | ChessGameV3 game = new ChessGameV3(); 22 | game.setPlayers(new Player("Mary"), new Player("Jack")); 23 | game.generateAllChess(); 24 | game.showAllChess(); 25 | } 26 | 27 | Chess makeChess(String name, int weight, int side, int loc) { 28 | return new Chess(name, weight, side, loc); 29 | } 30 | 31 | /* 32 | * Using Factory method to generate all chess. This will make the 33 | * chess generation more flexible, can be extended in the child class. 34 | */ 35 | void generateAllChess() { 36 | black = new Chess[] { makeChess("將", 1, BLACK, 0), 37 | makeChess("士", 2, BLACK, 1), makeChess("士", 2, BLACK, 2), 38 | makeChess("象", 3, BLACK, 3), makeChess("象", 3, BLACK, 4), 39 | makeChess("車", 3, BLACK, 5), makeChess("車", 3, BLACK, 6), 40 | makeChess("馬", 3, BLACK, 7), makeChess("馬", 3, BLACK, 8), 41 | makeChess("包", 3, BLACK, 9), makeChess("包", 3, BLACK, 10), 42 | makeChess("卒", 3, BLACK, 11), makeChess("卒", 3, BLACK, 12), 43 | makeChess("卒", 3, BLACK, 13), makeChess("卒", 3, BLACK, 14), 44 | makeChess("卒", 3, BLACK, 15), }; 45 | 46 | red = new Chess[] { makeChess("帥", 1, RED, 16), 47 | makeChess("仕", 2, RED, 17), makeChess("仕", 2, RED, 18), 48 | makeChess("相", 3, RED, 19), makeChess("相", 3, BLACK, 20), 49 | makeChess("俥", 3, BLACK, 21), makeChess("俥", 3, BLACK, 22), 50 | makeChess("傌", 3, BLACK, 23), makeChess("傌", 3, BLACK, 24), 51 | makeChess("炮", 3, BLACK, 25), makeChess("炮", 3, BLACK, 26), 52 | makeChess("兵", 3, BLACK, 27), makeChess("兵", 3, BLACK, 28), 53 | makeChess("兵", 3, BLACK, 29), makeChess("兵", 3, BLACK, 30), 54 | makeChess("兵", 3, BLACK, 31), }; 55 | 56 | // change black's location 57 | for (int i = 0; i < 16; i++) { 58 | int target = (int) (Math.random() * 32); 59 | if (target < 16) { 60 | int originalLoc = black[i].loc; 61 | black[i].loc = target; 62 | black[target].loc = originalLoc; 63 | } else if (target < 32) { 64 | target -= 16; 65 | int originalLoc = black[i].loc; 66 | black[i].loc = target; 67 | red[target].loc = originalLoc; 68 | } else { 69 | System.out.println("Location Error"); 70 | } 71 | } 72 | 73 | } 74 | 75 | @Override 76 | void setPlayers(Player p1, Player p2) { 77 | this.p1 = p1; 78 | this.p2 = p2; 79 | } 80 | 81 | void showAllChess() { 82 | System.out.println("Players: " + p1 + " vs. " + p2); 83 | for (Chess c : black) { 84 | System.out.println(c); 85 | } 86 | for (Chess c : red) { 87 | System.out.println(c); 88 | } 89 | } 90 | 91 | } 92 | 93 | class Chess { 94 | // name, weight, side (black/red), location (1-32) 95 | public Chess(String name, int weight, int side, int loc) { 96 | this.name = name; 97 | this.weight = weight; 98 | this.side = side; 99 | this.loc = loc; 100 | } 101 | 102 | String name; 103 | int weight; 104 | int side; 105 | int loc; 106 | 107 | public String toString() { 108 | return name + ", \t" + weight + ", loc=" + this.getLocation(); 109 | } 110 | 111 | public Location getLocation() { 112 | return Location.getLocation(loc); 113 | } 114 | 115 | public int getLoc() { 116 | return loc; 117 | } 118 | } 119 | 120 | class Player { 121 | String name; 122 | 123 | public Player(String n) { 124 | this.name = n; 125 | } 126 | 127 | public String toString() { 128 | return name; 129 | } 130 | } 131 | 132 | /* 133 | * Location of a chess. It is composed of (x,y) x should be in the range (0,3), 134 | * y: (0, 7) 135 | */ 136 | class Location { 137 | int x, y; 138 | 139 | public Location(int x, int y) { 140 | boolean xOK = (x >= 0 && x <= 3); 141 | boolean yOK = (y >= 0 && y <= 7); 142 | if (!(xOK && yOK)) { 143 | System.out.println("Location Error:" + x + ", " + y); 144 | System.exit(0); 145 | } 146 | this.x = x; 147 | this.y = y; 148 | } 149 | 150 | public String toString() { 151 | return "(" + x + ", " + y + ")"; 152 | } 153 | 154 | public static Location getLocation(int loc) { 155 | int x = (loc / 8); 156 | int y = (loc % 8); 157 | return new Location(x, y); 158 | } 159 | } -------------------------------------------------------------------------------- /src/uml/GradeBookApp3.java: -------------------------------------------------------------------------------- 1 | /* 2 | USE relationship 3 | To implement the "score" relationship 4 | >This version is enhanced from version 2a 5 | 6 | * add Teacher.score(Course, Student, int) 7 | * add Student.showGrade(), to show all course he takes and the grade. 8 | * modify Course.showCourseInfo(), to show students' grade 9 | 10 | To complete the operation, we also add the following small methods 11 | * Course.getIndex(Student), to get the index of a student in the course 12 | * boolean Course.takenBy(Student), to check if the course is taken by a student 13 | * Course.score(Student, int), to score the grade of the student 14 | 15 | In the Teacher.score(Course, Student, int), Teacher has a "use" relationship 16 | to Student, since it does not have the reference to Student 17 | */ 18 | 19 | public class GradeBookApp3 { 20 | public static void main(String args[]) { 21 | Student Jie = new Student ("Jie"); 22 | Student Albert = new Student ("Albert"); 23 | 24 | Teacher Nick = new Teacher ("Nick"); 25 | 26 | Course Java = new Course ("Java", 3); 27 | Course Python = new Course ("Python", 3); 28 | 29 | Nick.offer(Java); 30 | Nick.offer(Python); 31 | 32 | Jie.takeCourse(Java); 33 | Albert.takeCourse(Java); 34 | 35 | Nick.score(Java, Jie, 100); //++++++++++ 36 | Nick.score(Java, Albert, 98); //++++++++++ 37 | Java.showCourseInfo(); //++++++++++ 38 | Jie.showGrade(); //++++++++++ 39 | Albert.showGrade(); //++++++++++ 40 | } 41 | 42 | } 43 | 44 | class Course { 45 | String cName; 46 | private int degree; 47 | Student[] students = new Student[10]; 48 | int studentCount = 0; 49 | Teacher teacher = new Teacher("None"); 50 | int [] grades = new int[10]; //++++++++++ 51 | 52 | public Course (String name, int degree) { 53 | this.cName = name; 54 | this.degree = degree; 55 | } 56 | 57 | public void registeredBy(Student s) { 58 | if (studentCount <= 9) 59 | students[studentCount++] = s; 60 | else 61 | System.out.println("Students overflow in a class"); 62 | } 63 | 64 | public void showCourseInfo() { //********** 65 | System.out.println("Course: "+ cName); 66 | System.out.println("-- Teacher: " + teacher.tName); 67 | String s = ""; 68 | String g = ""; 69 | for (int i=0; i teachers = new ArrayList(); 49 | ArrayList students = new ArrayList(); 50 | ArrayList courses = new ArrayList(); 51 | Map, Integer> gbook = new HashMap, Integer>(); 52 | 53 | public University(String s) { 54 | name = s; 55 | } 56 | 57 | public void setScore(Course c, Student s, int g) { 58 | gbook.put(new Pair(c, s), g); 59 | } 60 | 61 | public void showNoPass() { 62 | for (Entry, Integer> e : gbook.entrySet()) { 63 | if (e.getValue() < 60) { 64 | System.out.print("\nNo Pass Course: " + e.getKey().c); 65 | System.out.print("\t Student: " + e.getKey().s.name + "\tScore: " + e.getValue()); 66 | } 67 | } 68 | } 69 | 70 | public void showCourses() { 71 | System.out.println("\nThe courses offered by " + name + " are " + courses.toString()); 72 | 73 | } 74 | 75 | public void showMembers() { 76 | System.out.print("MEMBERS of " + name + ":"); 77 | System.out.print("\nThe teachers: "); 78 | for (Teacher t : teachers) { 79 | System.out.print(t.name + "\t"); 80 | } 81 | System.out.print("\nThe students: "); 82 | for (Student s : students) { 83 | System.out.print(s.name + "\t"); 84 | } 85 | } 86 | 87 | public void hire(Teacher t) { 88 | teachers.add(t); 89 | t.setUniversity(this); 90 | } 91 | 92 | public void registered(Student s) { 93 | students.add(s); 94 | s.setUniversity(this); 95 | } 96 | 97 | public void showAverage(Course c) { 98 | double sum = 0; 99 | int count = 0; 100 | for (Entry, Integer> e : gbook.entrySet()) { 101 | if (e.getKey().c.equals(c)) { 102 | sum += e.getValue(); 103 | count++; 104 | } 105 | } 106 | System.out.printf("\nAverage of the course %s is %.2f", c.toString(), sum / count); 107 | } 108 | 109 | public void addCourse(Course c) { 110 | courses.add(c); 111 | } 112 | 113 | public Iterator, Integer>> getGBookIterator() { 114 | Iterator, Integer>> it = gbook.entrySet().iterator(); 115 | return it; 116 | } 117 | } 118 | 119 | class Member { 120 | String name; 121 | University school; 122 | 123 | public Member(String n) { 124 | this.name = n; 125 | } 126 | 127 | public void setUniversity(University u) { 128 | this.school = u; 129 | } 130 | } 131 | 132 | class Teacher extends Member { 133 | ArrayList courses = new ArrayList(); 134 | 135 | public Teacher(String n) { 136 | super(n); 137 | } 138 | 139 | public void showAverage(Course c) { 140 | school.showAverage(c); 141 | } 142 | 143 | public void score(Course c, Student s, int g) { 144 | if (courses.contains(c)) 145 | school.setScore(c, s, g); 146 | else 147 | System.out.println("The teacher can't score this course"); 148 | } 149 | 150 | public void offer(Course c) { 151 | courses.add(c); 152 | school.addCourse(c); 153 | c.setTeacher(this); 154 | } 155 | 156 | } 157 | 158 | class Course { 159 | String name; 160 | Teacher t; 161 | ArrayList students = new ArrayList(); 162 | 163 | public Course(String c) { 164 | name = c; 165 | } 166 | 167 | public void setTeacher(Teacher t) { 168 | this.t = t; 169 | } 170 | 171 | public void listGrade() { 172 | Iterator, Integer>> gb = t.school.getGBookIterator(); 173 | System.out.print("\nThe grade of the course are: "); 174 | while (gb.hasNext()) { 175 | Entry, Integer> s = gb.next(); 176 | if (s.getKey().getCourse().equals(this)) 177 | System.out.print(s.getValue() + "\t"); 178 | } 179 | } 180 | 181 | public String toString() { 182 | return name; 183 | } 184 | 185 | public void addStudent(Student s) { 186 | students.add(s); 187 | } 188 | 189 | } 190 | 191 | class Pair { 192 | Course c; 193 | Student s; 194 | 195 | public Pair(Course c, Student s) { 196 | this.c = c; 197 | this.s = s; 198 | } 199 | 200 | public Course getCourse() { 201 | return c; 202 | } 203 | 204 | public Student getStudent() { 205 | return s; 206 | } 207 | 208 | public boolean equals(Object otherPair) { 209 | if (!(otherPair instanceof Pair)) 210 | return false; 211 | Pair p = (Pair)otherPair; 212 | return this.c.equals(p.c) && this.s.equals(p.s); 213 | } 214 | } 215 | 216 | class Student extends Member { 217 | 218 | public Student(String n) { 219 | super(n); 220 | } 221 | 222 | public void takeCourse(Course c) { 223 | c.addStudent(this); 224 | } 225 | 226 | public void enter(University fcu) { 227 | fcu.registered(this); 228 | 229 | } 230 | } 231 | -------------------------------------------------------------------------------- /src/chess/chessv4/ChessGameV4.java: -------------------------------------------------------------------------------- 1 | package chess.chessv4; 2 | 3 | import java.util.HashMap; 4 | import java.util.Map; 5 | 6 | /* 7 | * 規範每一個遊戲都應該有兩個玩家 8 | */ 9 | abstract class AbstractGame { 10 | abstract void setPlayers(Player p1, Player p2); 11 | } 12 | 13 | /* 14 | * Version 4 採用 Strategy 讓棋子的初始位置可以彈性設定。 15 | * 新增了棋盤類別 ChessBoard, 記錄每一個位置對應的棋子,也提供介面讓使用者對某個位子進行選擇、吃子的動作。 16 | */ 17 | public class ChessGameV4 extends AbstractGame { 18 | public static final int BLACK = 0, RED = 1; 19 | Chess[] chesses; 20 | Player p1, p2; 21 | 22 | public static void main(String args[]) { 23 | // initialize the game 24 | ChessGameV4 game = new ChessGameV4(); 25 | game.setPlayers(new Player("Mary"), new Player("Jack")); 26 | game.generateAllChess(); 27 | ChessBoard cb = new ChessBoard(); 28 | // game.setChessBoarding(cb, new SimpleChessBoarding()); 29 | game.setChessBoarding(cb, new RandomChessBoarding()); 30 | 31 | // 模擬一些使用者的行為 32 | cb.select(12); 33 | cb.kill(13); 34 | 35 | cb.showBoard(); 36 | } 37 | 38 | protected void setChessBoarding(ChessBoard cb, ChessBoarding boarding) { 39 | boarding.setLocation(chesses); 40 | cb.putChess(chesses); 41 | } 42 | 43 | Chess makeChess(String name, int side) { 44 | return new Chess(name, side); 45 | } 46 | 47 | /* 48 | * 採用 Factory Method 來產生棋子 49 | */ 50 | void generateAllChess() { 51 | chesses = new Chess[] { makeChess("將", BLACK), makeChess("士", BLACK), 52 | makeChess("士", BLACK), makeChess("象", BLACK), 53 | makeChess("象", BLACK), makeChess("車", BLACK), 54 | makeChess("車", BLACK), makeChess("馬", BLACK), 55 | makeChess("馬", BLACK), makeChess("包", BLACK), 56 | makeChess("包", BLACK), makeChess("卒", BLACK), 57 | makeChess("卒", BLACK), makeChess("卒", BLACK), 58 | makeChess("卒", BLACK), makeChess("卒", BLACK), 59 | makeChess("帥", RED), makeChess("仕", RED), makeChess("仕", RED), 60 | makeChess("相", RED), makeChess("相", BLACK), 61 | makeChess("俥", BLACK), makeChess("俥", BLACK), 62 | makeChess("傌", BLACK), makeChess("傌", BLACK), 63 | makeChess("炮", BLACK), makeChess("炮", BLACK), 64 | makeChess("兵", BLACK), makeChess("兵", BLACK), 65 | makeChess("兵", BLACK), makeChess("兵", BLACK), 66 | makeChess("兵", BLACK) }; 67 | } 68 | 69 | void setPlayers(Player p1, Player p2) { 70 | this.p1 = p1; 71 | this.p2 = p2; 72 | } 73 | 74 | void showAllChess() { 75 | System.out.println("Players: " + p1 + " vs. " + p2); 76 | for (Chess c : chesses) { 77 | System.out.println(c); 78 | } 79 | } 80 | } 81 | 82 | class Chess { 83 | public static final int CREATED = 0; 84 | public static final int SELECTED = 1; 85 | public static final int KILLED = 2; 86 | 87 | private String name; 88 | private int weight; 89 | private int side; 90 | private int loc; 91 | private int status; 92 | 93 | public Chess(String name, int side) { 94 | this.name = name; 95 | this.side = side; 96 | status = Chess.CREATED; 97 | } 98 | 99 | public String getName() { 100 | return name; 101 | } 102 | 103 | public Location getLocation() { 104 | return Location.getLocation(loc); 105 | } 106 | 107 | public int getLoc() { 108 | return loc; 109 | } 110 | 111 | void setLoc(int i) { 112 | this.loc = i; 113 | } 114 | 115 | public String toString() { 116 | return name + "," + " loc=" + getLocation() + ", staus =" + status; 117 | } 118 | 119 | public void setStatus(int s) { 120 | this.status = s; 121 | } 122 | 123 | // 是否被選了 124 | public boolean isSelected() { 125 | return status == Chess.SELECTED ? true : false; 126 | } 127 | } 128 | 129 | class Player { 130 | String name; 131 | 132 | public Player(String n) { 133 | this.name = n; 134 | } 135 | 136 | public String toString() { 137 | return name; 138 | } 139 | } 140 | 141 | /* 142 | * Location of a chess. It is composed of (x,y) x should be in the range (0,3), 143 | * y: (0, 7) 144 | */ 145 | class Location { 146 | int x, y; 147 | 148 | public Location(int loc) { 149 | this(loc / 8, loc % 8); 150 | } 151 | 152 | public Location(int x, int y) { 153 | boolean xOK = (x >= 0 && x <= 3); 154 | boolean yOK = (y >= 0 && y <= 7); 155 | if (!(xOK && yOK)) { 156 | System.out.println("Location Error:" + x + ", " + y); 157 | System.exit(0); 158 | } 159 | this.x = x; 160 | this.y = y; 161 | } 162 | 163 | public String toString() { 164 | return "(" + x + ", " + y + ")"; 165 | } 166 | 167 | public static Location getLocation(int loc) { 168 | int x = (loc / 8); 169 | int y = (loc % 8); 170 | return new Location(x, y); 171 | } 172 | 173 | int getLoc() { 174 | int result = 8 * x + y; 175 | return result; 176 | } 177 | } 178 | 179 | class ChessBoard { 180 | // board 記錄每一個 Location 對應的棋子 181 | Map board = new HashMap(); 182 | Location[] locs; 183 | Chess[] chesses; 184 | 185 | // put the chess to the board 186 | public void putChess(Chess[] chesses) { 187 | this.chesses = chesses; 188 | locs = new Location[chesses.length]; 189 | for (int i = 0; i < chesses.length; i++) { 190 | locs[i] = new Location(i); 191 | } 192 | for (int i = 0; i < chesses.length; i++) { 193 | Chess c = chesses[i]; 194 | int loc = c.getLoc(); 195 | board.put(locs[loc], c); 196 | } 197 | } 198 | 199 | public void kill(int loc) { 200 | Chess c = (Chess) board.get(locs[loc]); 201 | c.setStatus(Chess.KILLED); 202 | board.put(locs[loc], null); 203 | } 204 | 205 | public void select(int loc) { 206 | Chess c = (Chess) board.get(locs[loc]); 207 | c.setStatus(Chess.SELECTED); 208 | } 209 | 210 | void showBoard() { 211 | for (int i = 0; i < locs.length; i++) { 212 | Chess c = (Chess) (board.get(locs[i])); 213 | boolean noChessOnLocation = (c == null) ? true : false; 214 | if (noChessOnLocation) 215 | System.out.print(" "); 216 | else if (c.isSelected()) 217 | System.out.print("[" + c.getName() + "]"); 218 | else 219 | System.out.print(c.getName()); 220 | // new row 221 | if ((i + 1) % 8 == 0) 222 | System.out.println(""); 223 | else 224 | System.out.print("\t"); 225 | } 226 | } 227 | } 228 | 229 | /* 230 | * 設定棋子位置的方法。Strategy 設計樣式中的 AbstractStrategy 231 | */ 232 | interface ChessBoarding { 233 | public void setLocation(Chess[] chesses); 234 | } 235 | 236 | /* 237 | * 隨機的設定棋子的位置 238 | */ 239 | class RandomChessBoarding implements ChessBoarding { 240 | 241 | public void setLocation(Chess[] chesses) { 242 | // initialize location 243 | for (int i = 0; i < chesses.length; i++) { 244 | chesses[i].setLoc(i); 245 | } 246 | // exchange location 247 | for (int i = 0; i < chesses.length / 2; i++) { 248 | int a = (int) (Math.random() * 32); 249 | int b = (int) (Math.random() * 32); 250 | Chess chessA = chesses[a]; 251 | Chess chessB = chesses[b]; 252 | int chessALocation = chessA.getLoc(); 253 | // switch the location 254 | chessA.setLoc(chessB.getLoc()); 255 | chessB.setLoc(chessALocation); 256 | } 257 | } 258 | } 259 | 260 | /* 261 | * 簡易的棋子排版,會依照 將士...卒帥仕...兵 的方式排版 262 | */ 263 | class SimpleChessBoarding implements ChessBoarding { 264 | public void setLocation(Chess[] chesses) { 265 | for (int i = 0; i < chesses.length; i++) { 266 | chesses[i].setLoc(i); 267 | } 268 | } 269 | } -------------------------------------------------------------------------------- /src/uml/GradeBookApp5.java: -------------------------------------------------------------------------------- 1 | /* 2 | INTERFACE and its implementation 3 | * a Instructor interface define the "teach" behavior 4 | * Teacher or IndustryExpert may server as an instructor 5 | * all instructors are required to set their Qualification 6 | 7 | * OCP principle 8 | * when we have different types of qualification, we use "extension", not 9 | modify the code 10 | 11 | 12 | * add an interface Instructor, methods: setQualification(Qualification) 13 | and showQualification() 14 | * add a new class IndustryExpert, to implement the Instructor 15 | * modify Teacher to implement the Instructor 16 | * add a Qualification subclass Certification, which requires the 17 | year getting the cerification. 18 | * add a static method to show all instructors 19 | */ 20 | 21 | public class GradeBookApp5 { 22 | public static void main(String args[]) { 23 | Student Jie = new Student ("Jie"); 24 | Student Albert = new Student ("Albert"); 25 | Student Alex = new Student ("Alex"); 26 | 27 | Teacher Nick = new Teacher ("Nick"); 28 | 29 | IndustryExpert Peter = new IndustryExpert("Peter"); //++++++++++ 30 | Nick.setQualification(new Qualification("IECS Ph.D")); //++++++++++ 31 | Peter.setQualification(new Certification(2000, "Cisco")); //++++++++++ 32 | Instructor tutors[] = {(Instructor)Nick, (Instructor)Peter}; //++++++++++ 33 | System.out.println("\n=== INSTRUCTORS QUALIFICATION ==="); //++++++++++ 34 | for (Instructor i: tutors) 35 | i.showQualification(); 36 | 37 | Albert.setEmail("albert@gmail.com"); 38 | Jie.setEmail("jie@gmail.com"); 39 | Nick.setEmail("nick@gmail.com"); 40 | 41 | Member[] members = {Albert, Jie, Nick}; 42 | System.out.println("\n=== MEMBERS ==="); //++++++++++ 43 | for (Member m: members) 44 | m.showInfo(); 45 | 46 | Course Java = new Course ("Java", 3); 47 | Course Python = new Course ("Python", 3); 48 | 49 | Nick.offer(Java); 50 | Nick.offer(Python); 51 | 52 | Jie.takeCourse(Java); 53 | Albert.takeCourse(Java); 54 | Alex.takeCourse(Java); 55 | 56 | Nick.score(Java, Jie, 100); 57 | Nick.score(Java, Albert, 98); 58 | Nick.score(Java, Alex, 20); 59 | 60 | Course[] courses = {Java, Python}; 61 | showCourses(courses); 62 | } 63 | 64 | public static void showCourses(Course[] courses) { //++++++++++ 65 | System.out.println("\n=== COURSES ==="); 66 | for (Course c: courses) 67 | c.showCourseInfo(); 68 | } 69 | 70 | } 71 | 72 | class Course { 73 | String cName; 74 | private int degree; 75 | Student[] students = new Student[10]; 76 | int studentCount = 0; 77 | Teacher teacher = new Teacher("None"); 78 | int [] grades = new int[10]; 79 | int scoreCount = 0; 80 | double sum=0; 81 | double average=0; 82 | 83 | public Course (String name, int degree) { 84 | this.cName = name; 85 | this.degree = degree; 86 | } 87 | 88 | public void registeredBy(Student s) { 89 | if (studentCount <= 9) 90 | students[studentCount++] = s; 91 | else 92 | System.out.println("Students overflow in a class"); 93 | } 94 | 95 | public void showCourseInfo() { 96 | System.out.println("Course: "+ cName); 97 | System.out.println("-- Teacher: " + teacher.name); 98 | String s = ""; 99 | String g = ""; 100 | for (int i=0; iMAX || g=90) level = "A"; 113 | if (v>=80 && v<90) level = "B"; 114 | if (v>=70 && v<80) level = "C"; 115 | if (v>=60 && v<70) level = "D"; 116 | if (v<60) level = "E"; 117 | return level; 118 | } 119 | 120 | public int v() { 121 | return v; 122 | } 123 | } 124 | 125 | class Course { 126 | String cName; 127 | private int degree; 128 | Student[] students = new Student[Config.MAX_STUDENT]; 129 | int studentCount = 0; 130 | Teacher teacher = new Teacher("None"); 131 | int [] grades = new int[Config.MAX_STUDENT]; 132 | int scoreCount = 0; 133 | double sum=0; 134 | double average=0; 135 | SortStrategy sorter; 136 | 137 | public Course (String name, int degree) { 138 | this.cName = name; 139 | this.degree = degree; 140 | 141 | for (int i=0; i< Config.MAX_STUDENT; i++) 142 | grades[i]=Grade.NOT_SCORE; 143 | } 144 | 145 | public void registeredBy(Student s) { 146 | if (studentCount <= Config.MAX_STUDENT-1) //********** 147 | students[studentCount++] = s; 148 | else 149 | System.out.println("Students overflow in a class"); 150 | } 151 | 152 | public void showCourseInfo() { 153 | System.out.println("Course: "+ cName); 154 | System.out.println("-- Teacher: " + teacher.name); 155 | String s = ""; 156 | String g = ""; 157 | for (int i=0; i board = new HashMap(); 292 | Location[] locs; 293 | Chess[] chesses; 294 | ChessGame game; // the game where the board plays on 295 | Chess selectedChess; 296 | 297 | // let chess board know game 298 | public ChessBoard(ChessGame g) { 299 | this.game = g; 300 | } 301 | 302 | // put the chess to the board 303 | public void putChess(Chess[] chesses) { 304 | this.chesses = chesses; 305 | locs = new Location[chesses.length]; 306 | for (int i = 0; i < chesses.length; i++) { 307 | locs[i] = new Location(i); 308 | } 309 | for (int i = 0; i < chesses.length; i++) { 310 | Chess c = chesses[i]; 311 | int loc = c.getLoc(); 312 | c.setLocation(locs[loc]); 313 | assert (c.getLocation() == locs[c.getLoc()]) : "Location setting error"; 314 | board.put(locs[loc], c); 315 | } 316 | } 317 | 318 | private void kill(Chess killer, Chess c) { 319 | // 先假設 killer 可以 kill c 320 | Location killerLocation = killer.getLocation(); 321 | board.put(killerLocation, null); 322 | board.put(c.getLocation(), killer); 323 | killer.move(c.getLoc()); 324 | killer.location = c.getLocation(); 325 | c.killed(); 326 | } 327 | 328 | private void select(Chess c) { 329 | c.select(); 330 | selectedChess = c; 331 | } 332 | 333 | private void move(Chess mover, int loc) { 334 | Location moverLocation = mover.getLocation(); 335 | System.out.println(moverLocation); 336 | board.put(moverLocation, null); // ! the move doesn't work 337 | board.put(locs[loc], mover); 338 | mover.move(loc); 339 | mover.location = locs[loc]; 340 | mover.unSelect(); 341 | } 342 | 343 | /* 344 | * 當使用者點擊 loc 位置時,依據當時的狀況判斷是 select, reselect, move or delete 345 | */ 346 | void target(int loc) { 347 | Chess c = (Chess) board.get(locs[loc]); 348 | if (c == null) { 349 | // move 350 | System.out.println(selectedChess.getName() + " move to " + loc); 351 | if (selectedChess != null) { 352 | move(selectedChess, loc); 353 | changeTurn(); 354 | } else { 355 | // user click the empty cell, do nothing 356 | } 357 | } 358 | // select or kill 359 | else { 360 | if (selectedChess == null) { 361 | if (game.nextTurn() == c.owner) { 362 | System.out.println(c.owner.name + " Select " + c.getName()); 363 | select(c); 364 | } else 365 | System.out.println("You can't select this chess"); 366 | } 367 | // reselect or kill 368 | else { 369 | // reselect 370 | if (game.nextTurn() == c.owner) { 371 | System.out.println(c.owner.name + " Reselect " 372 | + c.getName()); 373 | selectedChess.unSelect(); 374 | select(c); 375 | } else { 376 | Chess killer = selectedChess; 377 | System.out.println(killer.getName() + " kill " 378 | + c.getName()); 379 | kill(killer, c); 380 | changeTurn(); 381 | } 382 | } 383 | } 384 | } 385 | 386 | private void changeTurn() { 387 | game.changeTurn(); 388 | selectedChess.unSelect(); 389 | selectedChess = null; 390 | } 391 | 392 | void showBoard() { 393 | for (int i = 0; i < locs.length; i++) { 394 | Chess c = (Chess) (board.get(locs[i])); 395 | boolean noChessOnLocation = (c == null) ? true : false; 396 | if (noChessOnLocation) 397 | System.out.print(" "); 398 | else if (c.isSelected()) 399 | System.out.print("[" + c.getName() + "]"); 400 | else 401 | System.out.print(c.getName()); 402 | // new row 403 | if ((i + 1) % 8 == 0) 404 | System.out.println(""); 405 | else 406 | System.out.print("\t"); 407 | } 408 | System.out.println("Turn: " + game.nextTurn().name); 409 | } 410 | } 411 | --------------------------------------------------------------------------------