程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
 程式師世界 >> 編程語言 >> JAVA編程 >> 關於JAVA >> Java設計形式之原型形式(Prototype形式)引見

Java設計形式之原型形式(Prototype形式)引見

編輯:關於JAVA

Java設計形式之原型形式(Prototype形式)引見。本站提示廣大學習愛好者:(Java設計形式之原型形式(Prototype形式)引見)文章只能為提供參考,不一定能成為您想要的結果。以下是Java設計形式之原型形式(Prototype形式)引見正文


Prototype形式界說:用原型實例指定創立對象的品種,而且經由過程拷貝這些原型創立新的對象。

Prototype形式許可一個對象再創立別的一個可定制的對象,基本無需曉得任何若何創立的細節,任務道理是:經由過程將一個原型對象傳給誰人要動員創立的對象,這個要動員創立的對象經由過程要求原型對象拷貝它們本身來實行創立。

若何應用原型形式

由於Java中的供給clone()辦法來完成對象的克隆,所以Prototype形式完成一會兒變得很簡略。以勺子為例:

public abstract class AbstractSpoon implements Cloneable{
 String spoonName;
 public void setSpoonName(String spoonName) {this.spoonName = spoonName;}
 public String getSpoonName() {return this.spoonName;}
 public Object clone(){
  Object object = null;
  try {
   object = super.clone();
  } catch (CloneNotSupportedException exception) {
   System.err.println("AbstractSpoon is not Cloneable");
  }
   return object;
 }
}

有兩個詳細完成(ConcretePrototype):

public class SoupSpoon extends AbstractSpoon{
 public SoupSpoon(){
  setSpoonName("Soup Spoon");
 }
}
public class SaladSpoon extends AbstractSpoon{
 public SaladSpoon(){
  setSpoonName("Salad Spoon");
 }
}

挪用Prototype形式很簡略:

AbstractSpoon spoon = new SoupSpoon();
AbstractSpoon spoon = new SaladSpoon();

固然也能夠聯合工場形式來創立AbstractSpoon實例。

在Java中Prototype形式釀成clone()辦法的應用,因為Java的純粹的面向對象特征,使得在Java中應用設計形式變得很天然,二者曾經簡直是天衣無縫了。這反應在許多形式上,如Interator遍歷形式。

��源為麥克風 mMediaRecorder.setAudioSource(MediaRecorder.AudioSource.MIC); // 設置音頻格局 mMediaRecorder.setOutputFormat(MediaRecorder.OutputFormat.RAW_AMR); // 設置音頻編碼 mMediaRecorder.setAudioEncoder(MediaRecorder.AudioEncoder.AMR_NB); // 預備灌音 mMediaRecorder.prepare(); // 開端 mMediaRecorder.start(); // 預備停止 isPrepare = true; if (mAudioStateListener != null) { mAudioStateListener.wellPrepared(); } } catch (IllegalStateException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } /** * 隨機生成文件的稱號 */ private String generateFileName() { return UUID.randomUUID().toString() + ".amr"; } public int getVoiceLevel(int maxlevel) { if (isPrepare) { try { // mMediaRecorder.getMaxAmplitude() 1~32767 return maxlevel * mMediaRecorder.getMaxAmplitude() / 32768 + 1; } catch (Exception e) { } } return 1; } /** * 釋放資本 */ public void release() { //mMediaRecorder.stop(); mMediaRecorder.reset(); mMediaRecorder = null; } /** * 撤消灌音 */ public void cancel() { release(); if (mCurrentFilePath != null) { File file = new File(mCurrentFilePath); file.delete(); mCurrentFilePath = null; } } public String getCurrentFilePath() { return mCurrentFilePath; } }

AudioRecorderButton.java

package com.xuliugen.weichat;

import android.content.Context;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.util.AttributeSet;
import android.view.MotionEvent;
import android.view.View;
import android.widget.Button;

import com.xuliugen.weichat.R;
import com.xuliugen.weichat.AudioManager.AudioStateListener;

public class AudioRecorderButton extends Button {

 private static final int STATE_NORMAL = 1;// 默許的狀況
 private static final int STATE_RECORDING = 2;// 正在灌音
 private static final int STATE_WANT_TO_CANCEL = 3;// 願望撤消

 private int mCurrentState = STATE_NORMAL; // 以後的狀況
 private boolean isRecording = false;// 曾經開端灌音

 private static final int DISTANCE_Y_CANCEL = 50;

 private DialogManager mDialogManager;
 private AudioManager mAudioManager;

 private float mTime;
 // 能否觸發longClick
 private boolean mReady;

 private static final int MSG_AUDIO_PREPARED = 0x110;
 private static final int MSG_VOICE_CHANGED = 0x111;
 private static final int MSG_DIALOG_DIMISS = 0x112;

 /*
  * 獲得音量年夜小的線程
  */
 private Runnable mGetVoiceLevelRunnable = new Runnable() {

  public void run() {
   while (isRecording) {
    try {
     Thread.sleep(100);
     mTime += 0.1f;
     mHandler.sendEmptyMessage(MSG_VOICE_CHANGED);
    } catch (InterruptedException e) {
     e.printStackTrace();
    }
   }
  }
 };

 private Handler mHandler = new Handler() {

  @Override
  public void handleMessage(Message msg) {
   switch (msg.what) {
   case MSG_AUDIO_PREPARED:
    // 顯示對話框在開端灌音今後
    mDialogManager.showRecordingDialog();
    isRecording = true;
    // 開啟一個線程
    new Thread(mGetVoiceLevelRunnable).start();
    break;

   case MSG_VOICE_CHANGED:
    mDialogManager.updateVoiceLevel(mAudioManager.getVoiceLevel(7));
    break;

   case MSG_DIALOG_DIMISS:
    mDialogManager.dimissDialog();
    break;

   }

   super.handleMessage(msg);
  }
 };

 /**
  * 以下2個辦法是結構辦法
  */
 public AudioRecorderButton(Context context, AttributeSet attrs) {
  super(context, attrs);
  mDialogManager = new DialogManager(context);

  String dir = "/storage/sdcard0/my_weixin";
  //String dir = Environment.getExternalStorageDirectory()+"/my_weixin";

  mAudioManager = AudioManager.getInstance(dir);
  mAudioManager.setOnAudioStateListener(new AudioStateListener() {

   public void wellPrepared() {
    mHandler.sendEmptyMessage(MSG_AUDIO_PREPARED);
   }
  });

  // 因為這個類是button所以在結構辦法中添加監聽事宜
  setOnLongClickListener(new OnLongClickListener() {

   public boolean onLongClick(View v) {
    mReady = true;

    mAudioManager.prepareAudio();

    return false;
   }
  });
 }

 public AudioRecorderButton(Context context) {
  this(context, null);
 }

 /**
  * 灌音完成後的回調
  */
 public interface AudioFinishRecorderListener {
  void onFinish(float seconds, String filePath);
 }

 private AudioFinishRecorderListener audioFinishRecorderListener;

 public void setAudioFinishRecorderListener(AudioFinishRecorderListener listener) {
  audioFinishRecorderListener = listener;
 }

 /**
  * 屏幕的觸摸事宜
  */
 @Override
 public boolean onTouchEvent(MotionEvent event) {

  int action = event.getAction();
  int x = (int) event.getX();// 取得x軸坐標
  int y = (int) event.getY();// 取得y軸坐標

  switch (action) {
  case MotionEvent.ACTION_DOWN:
   changeState(STATE_RECORDING);
   break;
  case MotionEvent.ACTION_MOVE:

   if (isRecording) {
    // 假如想要撤消,依據x,y的坐標看能否須要撤消
    if (wantToCancle(x, y)) {
     changeState(STATE_WANT_TO_CANCEL);
    } else {
     changeState(STATE_RECORDING);
    }
   }

   break;
  case MotionEvent.ACTION_UP:
   if (!mReady) {
    reset();
    return super.onTouchEvent(event);
   }
   if (!isRecording || mTime < 0.6f) {
    mDialogManager.tooShort();
    mAudioManager.cancel();
    mHandler.sendEmptyMessageDelayed(MSG_DIALOG_DIMISS, 1000);// 延遲顯示對話框
   } else if (mCurrentState == STATE_RECORDING) { // 正在灌音的時刻,停止
    mDialogManager.dimissDialog();
    mAudioManager.release();

    if (audioFinishRecorderListener != null) {
     audioFinishRecorderListener.onFinish(mTime,mAudioManager.getCurrentFilePath());
    }

   } else if (mCurrentState == STATE_WANT_TO_CANCEL) { // 想要撤消
    mDialogManager.dimissDialog();
    mAudioManager.cancel();
   }
   reset();
   break;

  }
  return super.onTouchEvent(event);
 }

 /**
  * 恢復狀況及標記位
  */
 private void reset() {
  isRecording = false;
  mTime = 0;
  mReady = false;
  changeState(STATE_NORMAL);
 }

 private boolean wantToCancle(int x, int y) {
  if (x < 0 || x > getWidth()) { // 跨越按鈕的寬度
   return true;
  }
  // 跨越按鈕的高度
  if (y < -DISTANCE_Y_CANCEL || y > getHeight() + DISTANCE_Y_CANCEL) {
   return true;
  }

  return false;
 }

 /**
  * 轉變
  */
 private void changeState(int state) {
  if (mCurrentState != state) {
   mCurrentState = state;
   switch (state) {
   case STATE_NORMAL:
    setBackgroundResource(R.drawable.btn_recorder_normal);
    setText(R.string.str_recorder_normal);
    break;

   case STATE_RECORDING:
    setBackgroundResource(R.drawable.btn_recorder_recording);
    setText(R.string.str_recorder_recording);
    if (isRecording) {
     mDialogManager.recording();
    }
    break;

   case STATE_WANT_TO_CANCEL:
    setBackgroundResource(R.drawable.btn_recorder_recording);
    setText(R.string.str_recorder_want_cancel);

    mDialogManager.wantToCancel();
    break;
   }
  }
 }
}

DialogManager.java

package com.xuliugen.weichat;

import android.app.AlertDialog;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;

import com.xuliugen.weichat.R;

/**
 * 用於治理Dialog
 * 
 * @author xuliugen
 * 
 */
public class DialogManager {

 private AlertDialog.Builder builder;
 private ImageView mIcon;
 private ImageView mVoice;
 private TextView mLable;

 private Context mContext;

  private AlertDialog dialog;//用於撤消AlertDialog.Builder

 /**
  * 結構辦法 傳入高低文
  */
 public DialogManager(Context context) {
  this.mContext = context;
 }

 // 顯示灌音的對話框
 public void showRecordingDialog() {

  builder = new AlertDialog.Builder(mContext, R.style.AudioDialog);
  LayoutInflater inflater = LayoutInflater.from(mContext);
  View view = inflater.inflate(R.layout.dialog_recorder,null);

  mIcon = (ImageView) view.findViewById(R.id.id_recorder_dialog_icon);
  mVoice = (ImageView) view.findViewById(R.id.id_recorder_dialog_voice);
  mLable = (TextView) view.findViewById(R.id.id_recorder_dialog_label);

  builder.setView(view);
  builder.create();
  dialog = builder.show();
 }

 public void recording(){
  if(dialog != null && dialog.isShowing()){ //顯示狀況
   mIcon.setVisibility(View.VISIBLE);
   mVoice.setVisibility(View.VISIBLE);
   mLable.setVisibility(View.VISIBLE);

   mIcon.setImageResource(R.drawable.recorder);
   mLable.setText("手指上滑,撤消發送");
  }
 }

 // 顯示想撤消的對話框
 public void wantToCancel() {
  if(dialog != null && dialog.isShowing()){ //顯示狀況
   mIcon.setVisibility(View.VISIBLE);
   mVoice.setVisibility(View.GONE);
   mLable.setVisibility(View.VISIBLE);

   mIcon.setImageResource(R.drawable.cancel);
   mLable.setText("松開手指,撤消發送");
  }
 }

 // 顯示時光太短的對話框
 public void tooShort() {
  if(dialog != null && dialog.isShowing()){ //顯示狀況
   mIcon.setVisibility(View.VISIBLE);
   mVoice.setVisibility(View.GONE);
   mLable.setVisibility(View.VISIBLE);

   mIcon.setImageResource(R.drawable.voice_to_short);
   mLable.setText("灌音時光太短");
  }
 }

 // 顯示撤消的對話框
 public void dimissDialog() {
  if(dialog != null && dialog.isShowing()){ //顯示狀況
   dialog.dismiss();
   dialog = null;
  }
 }

 // 顯示更新音量級其余對話框
 public void updateVoiceLevel(int level) {
  if(dialog != null && dialog.isShowing()){ //顯示狀況
//   mIcon.setVisibility(View.VISIBLE);
//   mVoice.setVisibility(View.VISIBLE);
//   mLable.setVisibility(View.VISIBLE);

   //設置圖片的id
   int resId = mContext.getResources().getIdentifier("v"+level, "drawable", mContext.getPackageName());
   mVoice.setImageResource(resId);
  }
 }

}

MainActivity.java

package com.xuliugen.weichat;

import java.util.ArrayList;
import java.util.List;

import com.xuliugen.weichat.AudioRecorderButton.AudioFinishRecorderListener;

import android.app.Activity;
import android.graphics.drawable.AnimationDrawable;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.AdapterView.OnItemClickListener;

public class MainActivity extends Activity {
 private ListView mListView;

 private ArrayAdapter<Recorder> mAdapter;
 private List<Recorder> mDatas = new ArrayList<MainActivity.Recorder>();

 private AudioRecorderButton mAudioRecorderButton;

 private View animView;

 @Override
 protected void onCreate(Bundle savedInstanceState) {
  super.onCreate(savedInstanceState);
  setContentView(R.layout.activity_main);

  mListView = (ListView) findViewById(R.id.id_listview);
  mAudioRecorderButton = (AudioRecorderButton) findViewById(R.id.id_recorder_button);


  mAudioRecorderButton.setAudioFinishRecorderListener(new AudioFinishRecorderListener() {

   public void onFinish(float seconds, String filePath) {
    Recorder recorder = new Recorder(seconds, filePath);
    mDatas.add(recorder);
    mAdapter.notifyDataSetChanged(); //告訴更新的內容
    mListView.setSelection(mDatas.size() - 1); //將lisview設置為最初一個
   }
  });

  mAdapter = new RecoderAdapter(this, mDatas);
  mListView.setAdapter(mAdapter);

  //listView的item點擊事宜
  mListView.setOnItemClickListener(new OnItemClickListener() {

   public void onItemClick(AdapterView<?> arg0, View view,int position, long id) {
    // 播放動畫(幀動畫)
    if (animView != null) {
     animView.setBackgroundResource(R.drawable.adj);
     animView = null;
    }
    animView = view.findViewById(R.id.id_recoder_anim);
    animView.setBackgroundResource(R.drawable.play_anim);
    AnimationDrawable animation = (AnimationDrawable) animView.getBackground();
    animation.start();
    // 播放灌音
    MediaManager.playSound(mDatas.get(position).filePath,new MediaPlayer.OnCompletionListener() {

      public void onCompletion(MediaPlayer mp) {
       animView.setBackgroundResource(R.drawable.adj);
      }
     });
   }
  });
 }

 @Override
 protected void onPause() {
  super.onPause();
  MediaManager.pause();
 }

 @Override
 protected void onResume() {
  super.onResume();
  MediaManager.resume();
 }

 @Override
 protected void onDestroy() {
  super.onDestroy();
  MediaManager.release();
 }

 class Recorder {
  float time;
  String filePath;

  public Recorder(float time, String filePath) {
   super();
   this.time = time;
   this.filePath = filePath;
  }

  public float getTime() {
   return time;
  }

  public void setTime(float time) {
   this.time = time;
  }

  public String getFilePath() {
   return filePath;
  }

  public void setFilePath(String filePath) {
   this.filePath = filePath;
  }

 }

}

MediaManager.java

package com.xuliugen.weichat;

import android.media.AudioManager;
import android.media.MediaPlayer;
import android.media.MediaPlayer.OnCompletionListener;
import android.media.MediaPlayer.OnErrorListener;

public class MediaManager {

 private static MediaPlayer mMediaPlayer; 
 private static boolean isPause;

 /**
  * 播放音樂
  * @param filePath
  * @param onCompletionListener
  */
 public static void playSound(String filePath,OnCompletionListener onCompletionListener) {
  if (mMediaPlayer == null) {
   mMediaPlayer = new MediaPlayer();

   //設置一個error監聽器
   mMediaPlayer.setOnErrorListener(new OnErrorListener() {

    public boolean onError(MediaPlayer arg0, int arg1, int arg2) {
     mMediaPlayer.reset();
     return false;
    }
   });
  } else {
   mMediaPlayer.reset();
  }

  try {
   mMediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
   mMediaPlayer.setOnCompletionListener(onCompletionListener);
   mMediaPlayer.setDataSource(filePath);
   mMediaPlayer.prepare();
   mMediaPlayer.start();
  } catch (Exception e) {

  }
 }

 /**
  * 暫停播放
  */
 public static void pause() {
  if (mMediaPlayer != null && mMediaPlayer.isPlaying()) { //正在播放的時刻
   mMediaPlayer.pause();
   isPause = true;
  }
 }

 /**
  * 以後是isPause狀況
  */
 public static void resume() {
  if (mMediaPlayer != null && isPause) { 
   mMediaPlayer.start();
   isPause = false;
  }
 }

 /**
  * 釋放資本
  */
 public static void release() {
  if (mMediaPlayer != null) {
   mMediaPlayer.release();
   mMediaPlayer = null;
  }
 }
}

RecoderAdapter.java

package com.xuliugen.weichat;

import java.util.List;

import android.content.Context;
import android.util.DisplayMetrics;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.ArrayAdapter;
import android.widget.TextView;

import com.xuliugen.weichat.MainActivity.Recorder;

public class RecoderAdapter extends ArrayAdapter<Recorder> {

 private Context mContext;
 private List<Recorder> mDatas;

 private int mMinItemWidth; //最小的item寬度
 private int mMaxItemWidth; //最年夜的item寬度
 private LayoutInflater mInflater;

 public RecoderAdapter(Context context, List<Recorder> datas) {
  super(context, -1, datas);

  mContext = context;
  mDatas = datas;

  //獲得屏幕的寬度
  WindowManager wm = (WindowManager) context.getSystemService(Context.WINDOW_SERVICE);
  DisplayMetrics outMetrics = new DisplayMetrics();
  wm.getDefaultDisplay().getMetrics(outMetrics);
  mMaxItemWidth = (int) (outMetrics.widthPixels * 0.7f);
  mMinItemWidth = (int) (outMetrics.widthPixels * 0.15f);

  mInflater = LayoutInflater.from(context);
 }

 /**
  * 界說一個ViewHolder
  */
 private class ViewHolder {
  TextView seconds; // 時光
  View length; // 長度
 }

 @Override
 public View getView(int position, View convertView, ViewGroup parent) {
  ViewHolder holder = null;
  if (convertView == null) {
   convertView = mInflater.inflate(R.layout.item_recoder, parent,false);
   holder = new ViewHolder();
   holder.seconds = (TextView) convertView.findViewById(R.id.id_recoder_time);
   holder.length = convertView.findViewById(R.id.id_recoder_lenght);

   convertView.setTag(holder);

  } else {
   holder = (ViewHolder) convertView.getTag();
  }
  holder.seconds.setText(Math.round(getItem(position).time) + "\"");
  ViewGroup.LayoutParams lp = holder.length.getLayoutParams();
  lp.width = (int) (mMinItemWidth + (mMaxItemWidth / 60f)* getItem(position).time);
  return convertView;
 }
}

以上就是本文的全體內容,願望對年夜家的進修有所贊助。

  1. 上一頁:
  2. 下一頁:
Copyright © 程式師世界 All Rights Reserved