Amazon Ads

2015年10月12日 星期一

【筆記】用Java實作備忘錄(memoto)模式的簡單範例

嘗試用說故事的方弍來寫看看,XD Main.java
package idv.jk.study.designpattern.memoto;

/**
 * Created by bioyang on 2015/10/12.
 */
public class Main
{
    public static void main(String[] args)
    {
        //有一個叫小明的工程師
        Programmer smallMing = Programmer.beforeWork();
        //他在上班前的身心狀態
        System.out.printf("開始工作前的HP為 %d, 憤怒條為 %d\r\n", 
                            smallMing.getHitPoint(), smallMing.getAngryPoint());

        //為了確認明天是全新的一天,他的大腦要把上班前的狀態給記下來
        ProgrammerBrain brainOfSmallMing = new ProgrammerBrain();
        brainOfSmallMing.setBodyStateMemoto(smallMing.getBodyStateMemoto());

        //小明修了一個Bug
        smallMing.fixBug();
        //這對他的身心狀態沒有太大的影響
        System.out.printf("修了一個Bug的HP為 %d, 憤怒條為 %d\r\n", 
                            smallMing.getHitPoint(), smallMing.getAngryPoint());

        //客戶改了需求
        smallMing.requirementChanged();
        //要殺死一個工程師,只要改一個需求
        System.out.printf("知道客戶改了需求後的HP為 %d, 憤怒條為 %d\r\n", 
                            smallMing.getHitPoint(), smallMing.getAngryPoint());

        //但一天過去了,又是美好、新的一天
        smallMing.recoverBodyStateMemoto(brainOfSmallMing.getBodyStateMemoto());
        System.out.printf("隔天起床工作前的HP為 %d, 憤怒條為 %d\r\n", 
                            smallMing.getHitPoint(), smallMing.getAngryPoint());
    }
}
Programmer.java
package idv.jk.study.designpattern.memoto;

/**
 * Created by bioyang on 2015/10/12.
 */
public class Programmer
{
    /**
     * 生命值
     */
    private int hitPoint;
    /**
     * 憤怒條
     */
    private int angryPoint;

    private BodyStateMemoto mBodyStateMemoto;

    public BodyStateMemoto saveState()
    {
        return new BodyStateMemoto(this.hitPoint, this.angryPoint);
    }

    public static Programmer beforeWork()
    {
        Programmer programmer = new Programmer();
        programmer.setHitPoint(100);
        programmer.setAngryPoint(0);
        return programmer;
    }

    public void fixBug()
    {
        this.hitPoint -= 5;
        this.angryPoint += 10;
    }

    public void requirementChanged()
    {
        this.hitPoint = 0;
        this.angryPoint = 200;
    }

    public BodyStateMemoto getBodyStateMemoto()
    {
        return new BodyStateMemoto(getHitPoint(), getAngryPoint());
    }

    public void recoverBodyStateMemoto(BodyStateMemoto bodyStateMemoto)
    {
        setHitPoint(bodyStateMemoto.getHitPoint());
        setAngryPoint(bodyStateMemoto.getAngryLevel());
    }

    public int getHitPoint()
    {
        return hitPoint;
    }

    public void setHitPoint(int hitPoint)
    {
        this.hitPoint = hitPoint;
    }

    public int getAngryPoint()
    {
        return angryPoint;
    }

    public void setAngryPoint(int angryPoint)
    {
        this.angryPoint = angryPoint;
    }
}
BodyStateMemoto.java
package idv.jk.study.designpattern.memoto;

/**
 * Created by bioyang on 2015/10/12.
 */
public class BodyStateMemoto
{
    /**
     * 生命力
     */
    private int hitPoint;
    /**
     * 憤怒值
     */
    private int angryLevel;

    public BodyStateMemoto(int hitPoint, int angryLevel)
    {
        this.hitPoint = hitPoint;
        this.angryLevel = angryLevel;
    }

    public int getHitPoint()
    {
        return hitPoint;
    }

    public void setHitPoint(int hitPoint)
    {
        this.hitPoint = hitPoint;
    }

    public int getAngryLevel()
    {
        return angryLevel;
    }

    public void setAngryLevel(int angryLevel)
    {
        this.angryLevel = angryLevel;
    }
}
ProgrammerBrain.java
package idv.jk.study.designpattern.memoto;

/**
 * Created by bioyang on 2015/10/12.
 */
public class ProgrammerBrain
{
    private BodyStateMemoto mBodyStateMemoto;

    public void setBodyStateMemoto(BodyStateMemoto bodyStateMemoto)
    {
        this.mBodyStateMemoto = bodyStateMemoto;
    }

    public BodyStateMemoto getBodyStateMemoto()
    {
        return mBodyStateMemoto;
    }
}

2015年10月10日 星期六

【筆記】ReactJS呼叫外部API練習-顯示YouBike站點列表

最近有機會碰到React除了做完它的教學增加點自信外,再來嘗試做一些套用API的練習,這裡使用台北市政府提供的YouBike臺北市公共自行車即時資訊來取得YouBike站點資訊。

這裡拜歐先用 Node JS開一個網頁伺服器,主要是因為若用JavaScript去對上述的API送要求的話,會有Cross Domain呼叫的問題,會比較麻煩,所以這裡就用Node在伺服器送出要求,取回所需要的資料。

先寫一支名為server.js的程式:
var path = require('path');
var express = require('express');
var bodyParser = require('body-parser');
var app = express();
var request = require('request');

app.set('port', (process.env.PORT || 9999));

app.use('/', express.static(path.join(__dirname, 'public')));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({extended: true}));

app.get('/api/comments', function(req, res) {
 res.end('abc');
});

    app.get('/youbike/:pageSize/:offset', function(req, res){
    var pageSize = req.params.pageSize,
      offset = req.params.offset;
    request('http://data.taipei/opendata/datalist/apiAccess?scope=resourceAquire&rid=ddb80380-f1b3-4f8e-8016-7ed9cba571d5&limit=' + pageSize + '&offset=' + offset, 
        function(err, response, body){
          if(err)
          {
            console.log(err);
          }
          else if(response.statusCode == 200)
          {
            res.end(body);
          }
    })
    });

app.listen(app.get('port'), function() {
  console.log('Server started: http://localhost:' + app.get('port') + '/');
});
上列程式中,會用到Express這個Framwork,以及request這個package,它主要的功能就是在受到用戶端的要求時,再組成查詢的URLAPI送出要求,取回JSON格式的資料。

再來會有一支名為index.htmlHTML程式來顯示資料:
<!DOCTYPE html>
<html>
<head>
        
 
</head>
<body>
    
</body> </html>
那我們主要的 React是寫在youbiks.jsx中,其中主要定義了YouBikeSiteYouBikeSiteRowYouBikeTable等三個元件:
var YouBikeSite = React.createClass({
 getInitialState : function(){
  return {
   site : [],
  };
 },
   render : function(){
  var site = this.props.site;
    return (
     
{site.sno}
{site.sarea}
{site.sna}
{site.sbi}
{site.mday}
); } }); var YouBikeSiteRow = React.createClass({ render : function(){ console.log('YouBikeSiteList'); return (
{this.props.siteList.map(function(site) { //console.log(site); return (<YouBikeSite site={site} />); })}
); } }); var YouBikeTable = React.createClass({ getInitialState : function(){ return { siteList : [], page : 1 }; }, componentDidMount : function(){ this.loadYouBikeSiteInfo(); }, loadYouBikeSiteInfo : function(){ console.log('this.state.page: ' + this.state.page); var pageSize = 10, offset = (this.state.page >= 1 ? this.state.page - 1 : 0) * pageSize; console.log(offset); var youBikeSiteUrl = '/youbike/' + pageSize + '/' + offset; $.ajax({ url : youBikeSiteUrl, dataType : 'json', cache : false, success : function(data){ if(data.result && data.result.results) { this.setState({ siteList : data.result.results }); } //console.log(this.state.siteList); }.bind(this), error : function(xhr, status, err){ console.error(youBikeSiteUrl, status, err.toString()); }.bind(this) }); }, nextPage : function() { this.state.page += 1; this.loadYouBikeSiteInfo(); }, previousPage : function() { this.state.page -= 1; if(this.state.page < 0) { this.state.page = 0; } this.loadYouBikeSiteInfo(); }, render : function(){ return (

YouBike Site Information

場站代號
場站區域
場站名稱
目前車輛數
資料更新時間
<YouBikeSiteRow siteList={this.state.siteList}/>
) } }); ReactDOM.render( <YouBikeTable />, document.getElementById('container') );
完整的範例可以到 GitHub下載。

2015年9月23日 星期三

【筆記】用Java來做氣泡排序法的簡單範例

一直以來,想給自己補一下在演算法等基礎的不足,所以就從最基本的排序法開始,希望可以持續下去,XD

下列程式是拜歐依書中的範例改成Java版本的。
package idv.jk.study.algorithm.sort;

import java.util.Scanner;

/**
 * Created by javakid on 15/9/22.
 */
public class BubbleSort
{
    public static void main(String[] args)
    {
        int scores[] = new int[100];
        int size;
        System.out.println("輸入分數的總數...");
        Scanner scanner = new Scanner(System.in);

        size = scanner.nextInt();

        System.out.println("輸入分數(用,隔開)...");
        String strNumbers = scanner.next();

        String numbers[] = strNumbers.split(",");

        //把輸入的數字存入到陣列中
        for(int i = 0; i < numbers.length; i++)
        {
            scores[i] = Integer.parseInt(numbers[i]);
        }

        int temp;   //於大小比對時暫存數字的變數

        //開始對所有數字做排列
        for(int i = 0; i < size; i++)
        {
            //size - i表第2次只要比對size-1個數字,
            // 第3次只要比對size-2個數字,以此類推
            for (int j = 0; j < size - i; j++)
            {
                //由小至大,兩兩比對做數字交換
                if (scores[j] < scores[j+1])
                {
                    temp = scores[j];
                    scores[j] = scores[j+1];
                    scores[j+1] = temp;
                }
            }
        }

        //印出結果
        for(int i = 0; i < size; i++)
        {
            System.out.printf("%d ", scores[i]);
        }
    }
}
重點
  • 若有 n 個數字要進行排多,只需將 n-1 個數字歸位
  • 相鄰的數字比較後,依需要做大小交換
  • 時間複雜度為O(N2)

若真想打好演算法的底子,建議您拜歐正在念的這本:



2015年8月28日 星期五

【心得】初老宣言XD

圖片來源:https://images.unsplash.com/photo-1429198739803-7db875882052?q=80&fm=jpg&s=73fc6976c560896a0561a6d4119803a0

  • 趁年輕好好聽歌,好好流淚。

2015年8月27日 星期四

【筆記】Android Studio的快捷鍵

交互地用MacWindows,有些快捷鍵真的會忘,來記一下吧!

Mac快捷鍵 Windows快捷鍵 動作
Alt + ↑(方向鍵上)、Alt + ↓(方向鍵上) 在相鄰的方法間上下來回
command+ delete Ctrl + Y 刪除整行
command + fn + F12 Ctrl + F12 在類別中搜尋方法
command + N Alt + insert Generate,可以產生建構子、Getter、Setter、覆寫方法等
command + shift + U 選取的字串轉換大小寫
Ctrl + I Ctrl + I 實現(implement)介面或抽像類別的方法(method)

參考資料

2015年8月21日 星期五

【心得】工作上的一些想法

  • 某產品還沒受精時,就在想老闆怎麼會打分數,可以直接跟該產品說:「你已經死了」。
  • 愛抱怨的小孩,很難長大。
  • 做事不要只擔心著會被老闆打搶,偶爾也想想怎樣能給老闆打一槍。
  • 適時的溝通很重要,不要忍著讓原本可以討論的事變成抱怨;最後,把工作環境染成互相消費的氣圍。
  • 不要選擇太安逸的環境,這個時代,安逸代表很低的機會可以長進。